Java Solution with HashSet


  • 2
    R

    I use a set to hold all the numbers within the range of k. If it's in the set, then return true. If no number is every found in the set, then return false.

    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(nums.length == 0 || nums == null) return false;
        
        int n = nums.length;
    
        k = (k > nums.length) ? nums.length : k;
        HashSet<Integer> set = new HashSet<Integer>();
        
        for(int i = 0; i < nums.length; i++)
        {
            if(set.contains(nums[i])) {
                return true;
            }
            
            set.add(nums[i]);
            
            if(i >= k) {
                set.remove(nums[i - k]);
            }
        }
        
        return false;
    }

  • 0
    B

    why if(nums.length == 0 || nums == null)? If nums is null, you will got a NPE, right?


  • 0
    Z

    it may be better like this.

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

  • 0
    R

    Yeah thats right. I just added the error check just incase, but you don't need it to pass all the test cases.


  • 0
    L

    just flip the check around and it will shortcircuit if nums==null


  • 0
    B

    Yeah. That's what I mean


Log in to reply
 

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