Using sliding window and HashSet, O(n) complexity, JAVA code


  • 0
    F
    public boolean containsNearbyDuplicate(int[] nums,int k){
        Set<Integer> set=new HashSet<>();
        int i=0,j=0;
        while (j<nums.length){
            if(!set.contains(nums[j])){
                set.add(nums[j++]);
                if (j-i>k){
                    set.remove(nums[i++]);
                }
            }else {
                return true;
            }
        }
        return false;
    }

Log in to reply
 

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