题目
给你一个整数数组 nums 和一个整数 k ,判断数组中是否存在两个 不同的索引 i 和 j ,满足 nums[i] == nums[j]
且 abs(i - j) <= k
。如果存在,返回 true
;否则,返回 false
。
解题思路
维护一个 map
,遍历数组,每次将 nums[i]
对应的值更新为其下标 i
,如果存在重复元素,即键之前已存在,且之前的键对应的值与当前下标绝对值不大于 k
则返回 true
。
代码
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int length = nums.length;
for (int i = 0; i < length; i++) {
if (map.containsKey(nums[i])) {
if (Math.abs(i - map.get(nums[i])) <= k) return true;
}
map.put(nums[i], i);
}
return false;
}
}