Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such thatnums[i] = nums[j]and the difference betweeniandjis at mostk.
Subscribeto see which companies asked this question
Hide Tags ArrayHash Table Hide Similar Problems (E) Contains Duplicate(M) Contains Duplicate III
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set set = new HashSet();
for(int i=0;ik) set.remove(nums[i-k-1]);
if(!set.add(nums[i])) return true;
}
return false;
}
}