Easy java AC solution using hashmap, anyway to improve it?


  • 2
    F
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums.length <= 1) {return false;}
        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;}
            else {map.put(nums[i],i);}
        }
        return false;
    }
    

    }


  • 0
    J

    very good and easy to understand solution!! Thank you so much !!


  • 0
    T

    Another way is use a HashSet to store the closest k elements of the current element (at index i).

    Using a HashSet is slightly faster than using a HashMap.

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        
        Set<Integer> nearByElements = new HashSet<Integer>();
        
        for(int i=0; i<nums.length; i++){
            if(i > k){
                nearByElements.remove(nums[i-k-1]);
            }
            if(!nearByElements.add(nums[i])){
                return true;
            }
        }
        
        return false;
    }

Log in to reply
 

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