# Short AC JAVA solution

• ``````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;
}``````

• This post is deleted!

• nice solution.

• great solution

• I have a question on the test case:
[1,0,1,1]
1

So, we would put both index 0 and 2 to the key "1". And we we goto num[3]=1, it would get the index of the key "1", so whether hashmap.get(1) would return 0 or 2 is a random pick or not?

• @mirocody
It will always return 2, because `map.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 why

``````public 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;

}
}
``````

• @Evan100 I think you are map.put twice

• This post is deleted!

• @ceedifier

1. The above solution did not fail for the test case you mentioned.
2. I think your solution will exceed time limit for some test cases.

• This kind of methods will be TLE for current test case.