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 jis at most k.
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> hashSet = new HashSet<>();
int i = 0;
int j = 0;
for (; i < nums.length; i++) {
if (i - j > k) {
hashSet.remove(nums[j]);
j++;
}
if (hashSet.contains(nums[i])) {
return true;
}
hashSet.add(nums[i]);
}
return false;
}
}