Simple java solution with hashset


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.