思路:
(1)用Map存储从值到索引的映射。
(2)遍历数组,对每一个值,先判断其是否在Map中,若在,则将该值对应的索引减去该值映射到的索引,若所得差不大于k,则返回true。
(3)将该值映射到其所在的索引。
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = nums.length;
for (int i = 0; i < len; i++) {
if (map.containsKey(nums[i])) {
if (i - map.get(nums[i]) <= k)
return true;
}
map.put(nums[i], i);
}
return false;
}
}
Runtime:19ms