--- title: 'LeetCode 219. Contains Duplicate II' disqus: hackmd --- # LeetCode 219. Contains Duplicate II ## Description Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. ## Example Input: nums = [1,2,3,1], k = 3 Output: true Input: nums = [1,0,1,1], k = 1 Output: true Input: nums = [1,2,3,1,2,3], k = 2 Output: false ## Constraints 1 <= nums.length <= 10^5^ -10^9^ <= nums[i] <= 10^9^ 0 <= k <= 10^5^ ## Answer 此法可解但時間太久,用兩個for將每個item抓出來比較,內圈for就限制比較範圍,若達到就直接return true,若無就檢查到結束return false。 ```Cin= //2021_11_29 bool containsNearbyDuplicate(int* nums, int numsSize, int k) { int i = 0, j = 0, size = 0; for(i = 0; i < numsSize; i++){ for(j = i + 1; j < numsSize && j <= i + k; j++){ if(nums[i] == nums[j]){return true;} } } return false; } ``` ## Link https://leetcode.com/problems/contains-duplicate-ii/ ###### tags: `Leetcode`