Simple Java Solution With Comments


  • 0
    T
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        
        Map<Integer,Integer> map = new HashMap<>();
        
        for( int i=0; i<nums.length; i++ ){
            if( map.containsKey(nums[i]) ){
                int preIndex = map.get(nums[i]);
                if((i-preIndex)<=k){
                    return true;
                }                
            }
            map.put(nums[i],i); // update hashmap, otherwise the program will fail for case like
                                // nums={1,0,1,1} k = 1
                                // or put new key-value pairs in
        }
        return false;
    }

Log in to reply
 

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