My JAVA solution [Basic HashMap op!]


  • -1
    W
    public boolean containsNearbyDuplicate(int[] nums, int k) {
            
            int len = nums.length;
            Map<Integer, Integer> storage = new HashMap<Integer, Integer>();
            for(int i = 0; i < len; i++){
                if(storage.containsKey(nums[i])){
                    if(i - storage.get(nums[i]) <= k){
                        return true;
                    }else{
                        //replace/update prev map value with new index -- since we have moved past k
                        storage.put(nums[i], i);
                    }
                }else{
                    storage.put(nums[i], i);
                }
            }
            
            return false;
        }
    

    Hello! I believe that the code is fairly straightforward.

    However, should you have any queries about it, let me know!

    :)


  • 8
    A

    you could do "storage.put(nums[i], i);" only once

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

  • 0
    W

    Hello! You're right. Thanks for the feedback. :)


Log in to reply
 

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