219.Contains Duplicate II
Description
#219 | Contains Duplicate II | Medium | ||
---|---|---|---|---|
Array | Top 150 | |||
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 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Solution
Two-pointers
Runtime 2012ms |
|
Memory 58.45MB |
|
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k == 0) return false;
int left = 0, right = 1;
while(left < nums.length && right < nums.length) {
//System.out.println(left + " " + right);
if(nums[left] == nums[right])
return true;
if(right - left < k && right < nums.length -1)
right ++;
else {
left ++;
right = left + 1;
}
}
return false;
}
}
HashSet
Runtime 16ms |
|
Memory 56.88MB |
|
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k == 0 || nums.length < 2) return false;
Set<Integer> set = new HashSet<>();
for(int i = 0, j = 0; j < nums.length; j++) {
if(!set.add(nums[j])) return true;
if(set.size() >= k + 1)
set.remove(nums[i++]);
}
return false;
}
}