7 Line Simple Java Solution Using HashMap :)


  • 1
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i]) && (i - map.get(nums[i]) <= k)) return true;
            map.put(nums[i], i);
        }
        return false;
    }

  • 2

    The logic here is to add the number as the key, and index as the value. If this number appears again, check that the index difference is less than k : i - map.get(nums[i]) <= k. If it is not less than K, then update it with new index.


Log in to reply
 

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