力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
给你一个整数数组
nums
和一个整数k
,判断数组中是否存在两个 不同的索引i
和j
,满足nums[i] == nums[j]
且abs(i - j) <= k
。如果存在,返回true
;否则,返回false
。
题解:哈希,记录最大的已经存在的下标
代码如下:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums.length == 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i]) && i - map.get(nums[i]) <= k){
return true;
}
map.put(nums[i],i);
}
return false;
}
}