Keep a window of width k, before visit new element, remove nums[i - k - 1].
Other details are much the same as Contains Duplicate.
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> s = new HashSet<Integer>();
int N = nums.length;
for (int i = 0; i < N; ++i) {
if (i - k - 1 >= 0) s.remove(nums[i - k - 1]);
if (!s.add(nums[i])) return true;
}
return false;
}
}
leetcode 219. Contains Duplicate II
原文:https://www.cnblogs.com/exhausttolive/p/10667923.html