hashmap/hashset优化到O(n), 带一点滑动窗口思想。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_set<int> hashset;
int n = nums.size();
for(int i=0;i<n;i++){
if(hashset.count(nums[i])) return true;
else hashset.insert(nums[i]);
if(i>=k) hashset.erase(nums[i-k]);
}
return false;
}
};
用红黑树加lower_bound优化到O(nlogk)
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> treeSet;
for(int i=0;i<nums.size();i++){
auto it = treeSet.lower_bound((long long)nums[i]-t);
if(it!=treeSet.end()&&*it<=(long long)nums[i]+t) return true;
treeSet.insert(nums[i]);
if(treeSet.size()==k+1) treeSet.erase(nums[i-k]);
}
return false;
}
};