题目:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
思路:
由于这次需要查找的是一个和nums[i]的差值在t之内的数,所以不能简单地使用哈希表。另外一个重要的数据结构——二叉排序树就可以派上用场了。我们可以维护一个大小为k的二叉排序树,然后当每次扫描到一个nums[i]的时候,利用STL实现的lower_bound来查找 (nums[i] - t)的位置。由于lower_bound返回的是大于等于lower_bound的第一个数(也就是满足条件的最小数),所以我们可以安全地再次判断该数是否同时满足<= (nums[i] + t)。一旦满足,就可以直接返回。二叉排序树的插入、删除和查找的时间复杂度都是O(nlogn),所以本算法的时间复杂度是O(nlogn),空间复杂度是O(n)。
代码:
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> tree;
for(int i = 0; i < nums.size(); ++i) {
if(i > k) {
tree.erase(nums[i - k - 1]);
}
long long value = nums[i];
auto p = tree.lower_bound(value - t);
if(p != tree.end() && *p <= value + t) {
return true;
}
tree.insert(value);
}
return false;
}
};