JAVA Solution with hash map(Question: do I need to check null? )


  • 0
    S

    I read several solutions uploaded online. I mean if the input is null the answer will return the false as well. Do I also need to write the code to check it?

    public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
    Map hash = new HashMap<Integer,Integer>();

        for(int i=0; i<nums.length;i++){
            if(hash.containsKey(nums[i])){
                if((i-(int)hash.get(nums[i])) <= k)
                    return true;
                else hash.put(nums[i],i);
            }else{
                hash.put(nums[i],i);
            }
        }
        return false;
    }
    

    }


  • 0
    S

    You can simplify your two else like below:

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
            for(int i=0; i<nums.length; i++) {
                if(hm.containsKey(nums[i])) {
                    if((i-hm.get(nums[i])) <= k) {
                        return true;
                    }
                }
                hm.put(nums[i], i);
            }
            return false;
        }   
    }

Log in to reply
 

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