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.
代码
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t)
{
if (!k || t<0 || nums.size()<2)
return false;
//使用了set可以排序,大小为k,滑动窗口浏览,看窗口内部有没有小于t的
//重复:就必然存在,不重复:就可以用set
set<int> record;
auto nLen = nums.size();
for (int i = 0; i < nLen;++i)
{
if (i>k)
record.erase(nums[i - k - 1]); //两个相同时,早已return true
set<int>::iterator lower = record.lower_bound(nums[i] - t);
if (lower != record.end() && abs(nums[i] - *lower) <= t)
return true;
record.insert(nums[i]);
}
return false;
}
};