Contains Duplicate I
HashSet
add()
: add an element into hashset, if it has the element return false, otherwise return true.
Code
public class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> hs = new HashSet<Integer>();
for (int num: nums) {
// if the set already contains the element, the add() will return false
if (!hs.add(num)) {
return true;
}
}
return false;
}
}
Contains Duplicate II
Explanation
- use sliding window
- keep a window with size k using HashSet
- move forward one element, we deleted the last one and check if the window has an element as same as the new one.
Code
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> hs = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (!hs.add(nums[i])) {
return true;
}
if (i >= k) {
hs.remove(nums[i - k]);
}
}
return false;
}
}
Contains Duplicate III
TreeSet
floor(num)
: return the greatest element less than or equal to num.
ceiling(num)
: return the least element greater than or equal to num.
Explanation
Code
public class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> window = new TreeSet<Integer>();
for (int i = 0; i < nums.length; i++) {
Integer ceiling = window.ceiling(nums[i]);
Integer floor = window.floor(nums[i]);
if (ceiling != null && nums[i] >= ceiling - t) {
return true;
if (floor != null && nums[i] <= floor + t) {
return true;
window.add(nums[i]);
if (i >= k) {
window.remove(nums[i - k]);
}
return false;
}
}