(PS:算法很渣,也就简单的题能过)
基本思想很简单:HashSet查找还是挺快的,借助HashSet查找,在此也请各位大神不吝赐教!
import java.util.HashSet;
public class Solution2{
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashSet<Integer> set = new HashSet<>();
if(k<nums.length){
for (int i = 0; i <=k; i++) {
if(set.contains(nums[i]))return true;
set.add(nums[i]);
}
for (int i = k+1; i < nums.length; i++) {
set.remove(nums[i-k-1]);
if(set.contains(nums[i]))return true;
else{
set.add(nums[i]);
}
}
return false;
}
for (int i = 0; i < nums.length; i++) {
if(set.contains(nums[i]))return true;
set.add(nums[i]);
}
return false;
}
}