219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

// 用set,当i大于k的时候,把set中最前面的数字remove,
// 然后比较是否可以在加入set来判断是否有duplicate

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