JAVA SOLUTION USING HASHSET


  • -1
    N

    public boolean containsNearbyDuplicate(int[] nums, int k) {

        int length = nums.length;
        HashSet<Integer> result = new HashSet<>();
        
        for(int i = 0 ; i<length; i++)
        {
            if(result.contains(nums[i]))
            {
                for(int j = 0; j<i; j++)
                {
                    if(nums[i] == nums[j])
                    {
                        if((i-j) <= k)
                        {
                            return true;
                        }
                    }
                }
            }
            else
            {
                result.add(nums[i]);
            }
        }
        return false;
        
    }

Log in to reply
 

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