Poison

219. Contains Duplicate II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
// 窗口中元素数量:k + 1, eg: k = 1, window length = 2, when i = 1, start remove

Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (set.contains(nums[i])) {
return true;
}

set.add(nums[i]);
if (i - k >= 0) {
set.remove(nums[i - k]);
}
}

return false;
}
}
Reference

219. Contains Duplicate II