I use a set to hold all the numbers within the range of k. If it's in the set, then return true. If no number is every found in the set, then return false.

```
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums.length == 0 || nums == null) return false;
int n = nums.length;
k = (k > nums.length) ? nums.length : k;
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++)
{
if(set.contains(nums[i])) {
return true;
}
set.add(nums[i]);
if(i >= k) {
set.remove(nums[i - k]);
}
}
return false;
}
```