Solution 1: Use hash table and slide window
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set=new HashSet<>();
int i=0;
for (int j=0; j<nums.length; j++) {
if (j-i>k) set.remove(nums[i++]);
if (set.contains(nums[j])) return true;
set.add(nums[j]);
}
return false;
}
}
没有评论:
发表评论