Simple java solution


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

  • 0
    S

    so what if the same integer appears more than two times?


  • 0
    D

    it's ok,cause we travelsal the array in order,suppose there are 3 same integer x,x No1 would be saved by map first, when x No2 come out, calculate the diff,if diff <k, it's done,else update the x's index in hashmap, do the next round.


  • 0
    S

    thanks,I misunderstood the question~TAT


Log in to reply
 

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