219. Contains Duplicate II - Easy
前往題目
想法
Sliding window
思路
- 走訪
nums
- 使用
sliding window
,用hashset
記錄數字 - 當
window
大於k
,移除左指針數值,並且移動左指針 - 如果找到重複的數字,就回傳
true
Code
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int l = 0;
Set<Integer> window = new HashSet<>();
for (int r = 0; r < nums.length; ++r) {
// The window size is too large
if (r - l > k) {
window.remove(nums[l]); // Remove the leftmost element
++l; // move left pointer
}
// Found duplicate
if (window.contains(nums[r])) {
return true;
}
window.add(nums[r]);
}
return false;
}
}
219. Contains Duplicate II - Easy
https://f88083.github.io/2024/07/12/219-Contains-Duplicate-II/