My HashSet Solution. Easy to understand


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

Log in to reply
 

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