Java solution from a layman to another!


  • -1
    A

    public class Solution {

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

    HashSet<Integer> hs = new HashSet<Integer>();
    int len = nums.length;
    
    //if k is negative or zero, return false
    if(k<=0)
        return false;
    
    //fill hs with k elements
    //if any duplicate value encountered, return false
    for(int i=0; i<k && i<len ; i++)
        if(!hs.add(nums[i]))
            return true;
    
    //now start iterating the array from kth index
    for(int j=k; j<len ; j++)
        //if next element already exists in hs, return true
        if(hs.contains(nums[j]))
            return true;
        else
            {
               //remove the lowest index element in hs
                hs.remove(nums[j-k]);
                //add the current element
                hs.add(nums[j]);
            }
    
    //if code has reached this part, that means there were no duplicates in k distance from each other
    return false;
    

    }
    }


Log in to reply
 

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