JAVA O(n) HashTable solution


  • 0
    O
    //O(n)
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            if(nums.length == 0 || k == 0) return false;
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0; i < nums.length; i++){
                if(!map.containsKey(nums[i])){
                    map.put(nums[i],i);
                }else{
                    if(i - map.get(nums[i]) <= k) return true;
                    map.put(nums[i],i); //update the index of nums[i], always have the most recent index
                }
            }
            return false;
        }
    

Log in to reply
 

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