I used two pointers instead of a hashmap, and this solution beats 99.8% of Java solutions. Hope it helps!

```
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (k <= 0 || nums.length < 2) return false;
int left = 0, right = 1;
while (right < nums.length) {
if (left != right && nums[left] == nums[right]) return true;
int diff = right - left;
if (diff == k) {
left++;
} else {
right++;
}
}
while (left < right-1) {
if (nums[left++] == nums[right-1]) return true;
}
return false;
}
```