Java AC solution using a set


  • 0
    R
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            
            if(nums.length <= 1){
                return false;
            }
            
            Set<Integer> dupSet = new HashSet<Integer>();
            
            for(int i=0;i<nums.length;i++){
                if(dupSet.contains(nums[i]))
                   return true;
                else
                    dupSet.add(nums[i]);
                
                if(i >= k){
                    dupSet.remove(nums[i-k]);
                }
                
            }
        
        return false;
        }
    }
    

Log in to reply
 

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