Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
solution:
Use hashmap, key is the element value, value is the element index.
O(n)
public boolean containsNearbyDuplicate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return false;
Map<Integer, Integer> count = new HashMap<>();
for(int i = 0;i < len; i++) {
if(count.containsKey(nums[i])) {
if(Math.abs(count.get(nums[i]) - i) <= k) return true;
}
count.put(nums[i], i);
}
return false;
}