0
点赞
收藏
分享

微信扫一扫

存在重复元素 II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。

class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < nums.length;i ++){
if(map.containsKey(nums[i])){
if(i - map.get(nums[i]) <= k){
return true;
} else {
map.put(nums[i],i);
}
} else {
map.put(nums[i],i);
}
}
return false;
}
}

 

举报

相关推荐

0 条评论