题目:
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.
分析:
1、维护一个长度为k的窗口
2.要满足条件|nums[j] - num[i]| <= t,即nums[j] >= nums[i]-t && nums[j] <= nums[i]+t;
set的lower_bound(nums[i]-t)函数可以找到大于等于nums[i]-t的最小数,如果该数小于nums[i]+t,那么这个数和nums[i]就是满足条件的数对。
3.注意这里有int数的相加,和可能越界,所以set必须使用long long型
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.size() < 2 || k <= 0 || t < 0) return false;
int start = 0, end = 0;
set<long long> hashTable;
hashTable.insert(nums[0]);
for (int i = 1; i < nums.size(); ++i){
set<long long>::iterator iter = hashTable.lower_bound(nums[i] - t);
if (iter != hashTable.end() && *iter <= (long long)nums[i] + t) return true;
hashTable.insert(nums[i]);
end = i;
if (end - start == k){
hashTable.erase(nums[start]);
++start;
}
}
return false;
}
};