Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
两月没刷没手感了, nk的复杂度解法超时,
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int len=nums.size();
if (len<=1 || k==0 )
return false;
multiset<int> tree;
for (int i=0;i<nums.size();i++){
if (tree.size()>k)
tree.erase(nums[i-k-1]);
if (tree.size()>0){
multiset<int>::iterator low_bound=tree.lower_bound(nums[i]-abs(t));//返回>=nums[i]-abs(t)的第一个值;
multiset<int>::iterator up_bound=tree.lower_bound(nums[i]);//返回>nums[i]的第一个值;
if (low_bound!=tree.end() && abs(*low_bound-nums[i])<=t)
return true;
if (up_bound!=tree.end() && abs(*up_bound-nums[i])<=t)
return true;
}
tree.insert(nums[i]);
}
return false;
}
};