Contains Duplicate II
Input:
nums =
[1,2,3,1]
, k =
3
Output:
trueInput:
nums =
[1,0,1,1]
, k =
1
Output:
trueInput:
nums =
[1,2,3,1,2,3]
, k =
2
Output:
falseSolution
Using HashSet
HashMap
Last updated
Input:
nums =
[1,2,3,1]
, k =
3
Output:
trueInput:
nums =
[1,0,1,1]
, k =
1
Output:
trueInput:
nums =
[1,2,3,1,2,3]
, k =
2
Output:
falseLast updated
public boolean containsNearbyDuplicate(int[] nums, int k) {
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 (set.size() > k) {
set.remove(nums[i - k]);
}
}
return false;
}class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
int idx = map.get(nums[i]);
if (i - idx <= k) {
return true;
}
}
map.put(nums[i], i);
}
return false;
}
}