BiruLyu
6/12/2017 - 6:18 PM

219. Contains Duplicate II.java

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashSet<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < nums.length; i++) {
            if(set.size() > k) {
                set.remove(nums[i - k - 1]);
            }
            if(!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}
/*
[]
0
[1,2,3,4,1]
4
*/