Easy and clear solution by using HashMap (JAVA)


  • 1
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            //check to avoid nullpointexception
            if(nums == null){
                return false;
            }
            Map<Integer,Integer> check = new HashMap<Integer,Integer>();
            for(int i = 0; i < nums.length; i ++){
                if(check.containsKey(nums[i])){
                    if( i - check.get(nums[i]) <= k){
                        return true;
                    }
                }
                check.put(nums[i], i);
            }
            return false;
        }
    }

  • 0
    C

    Same idea here. The only difference is to check length of array and k value at first.

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

  • 0

    You are not considering the condition nums[i] = nums[j]


  • 0

    Sorry, but could your please give an example input that you think the code not handled.


  • 0
    Z

    he compare to nums[i] = nums[j] here:

    if(check.containsKey(nums[i]))


Log in to reply
 

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