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] andnums[j] is at most t and the difference between i and j is at most k.
一开始以为和前两道差不多,做了之后发现不太一样,如果用前两道题的方法,一般都会超时,即使判断t和k大小分别用不同的方式还是超时。
所以采用滑动窗口,保证map里面的所有key下标只差在k以内,然后找一个和nums[i]差值在t以内的值。
lower_bound(x)和upper_bound的区别:
lower_bound(x)返回一个key>=x的iterator
upper_bound(x)返回一个key>x的iterator
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
map<int, int> mp;
int j = 0;
map<int, int>::iterator it = mp.end();
for(int i = 0; i < nums.size(); i++){
if(i - j > k) mp.erase(nums[j++]);
it = mp.lower_bound(nums[i]-t);
if(it != mp.end() && it->first - nums[i] <= t)return true;
mp[nums[i]] = i;
}
return false;
}
};