本题题目要求如下:
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.
本题比本系列的前两道题要难了很多。。。我一开始没有想到最优解法,最优解法的思路是设置一个window,里面最多只有k+1个元素,如果超过这个数量,则删除第一个插入的。。这个靠set就可以实现。。。有abs(nums[i] - nums[j]) <= k,通过这个可以解出:nums[i] - k <= nums[j] <= nums[i] + k,如果在这个区间内存在值,则返回正确,如果一直没有符合的,则返回错误,具体的实现可以参考以下代码:
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.size() == 0 or k == 0) {
return false;
}
set<int> window;
int left = 0;
for (int i = 0; i < nums.size(); ++i) {
if (window.size() > k) {
window.erase(nums[left++]);
}
auto it_lb = window.lower_bound((long)nums[i] - (long)t);
if (it_lb != window.end() and *it_lb <= (long)t + (long)nums[i]) {
return true;
}
window.insert(nums[i]);
}
return false;
}
};