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 absolute difference between i and j is at most k.
思路:用哈希表記錄數字對應的位置,遍歷數組细疚,如果哈希表中已存在此數字小染,更新相距的最短距離,如果最短距離小于等于k,則返回true振愿。
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (k < 1) {
return false;
}
//record num => pos
HashMap<Integer, Integer> map = new HashMap<>();
//min distance
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i])) {
minDistance = Math.min(minDistance, i - map.get(nums[i]));
if (minDistance <= k) {
return true;
}
}
map.put(nums[i], i);
}
return false;
}