public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
if (i  map.get(nums[i]) <= k) return true;
}
map.put(nums[i], i);
}
return false;
}
Short AC JAVA solution

@mirocody
It will always return 2, becausemap.put(nums[i], i);
will update(nums[i],0)
from(1,0)
to(1,2)

@wz366
I used the same method as your, but time limited exceeded. not knowing whypublic class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.get(nums[i]) != null) { if (i  map.get(nums[i]) <= k) return true; else map.put(nums[i], i); } else { map.put(nums[i], i); } } return false; } }
