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;
}
};