给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
暴力法
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
for (int i = 0; i < nums.length-1; i++) {
for (int j = i+1; j < nums.length; j++) {
if(nums[i] == nums[j]&&Math.abs(i-j)<=k) return true;
}
}
return false;
}
}
哈希表
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map=new HashMap<>();
for (int i = 0; i <nums.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;
}
}
滑动窗口
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length <= 1) return false;
if(k <= 0) return false;
HashSet<Integer> sites = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if(sites.contains(nums[i])) return true;
sites.add(nums[i]);
if(sites.size() == k + 1)
sites.remove(nums[i-k]);
}
return false;
}
}