Question
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 -- HashMap
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int length = nums.length;
if (length <= 1 || k < 1)
return false;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int min = Integer.MAX_VALUE;
for (int i = 0; i < length; i++) {
if (map.containsKey(nums[i])) {
int prev = map.get(nums[i]);
int gap = i - prev;
min = Math.min(min, gap);
}
map.put(nums[i], i);
}
if (min <= k)
return true;
else
return false;
}
}