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.
最开始想到的是暴力,双重循环,时间复杂度为O(nk)
这道题是滑动窗口的题。找满足|i-j| <= k 的nums,同时满足|nums[i] - nums[j]| <=t
即 -t <=nums[i] - nums[j] <= t, so nums[i] - t <= nums[j] <= nums[i]+t
所以对于任意一个 nums[i] 只要满足在一个k长度的滑动窗口里即可
用set构造一个k长度的滑动窗口,然后每次检查[nums[i] - t, nums[i] + t]是否在是否包含在滑动窗口里,如果在那么说明存在另一个nums[j] 满足nums[i] - t <= nums[j] <= nums[i]+t ,且 i与j相差<=k
要注意数据范围,用long类型避免超int
代码如下:
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> window;
if (nums.size() <=1 || t < 0 || k < 1) return false;
for (int i = 0; i < nums.size(); i++) {
if (i > k) window.erase(nums[i-k-1]); //更新滑动窗口
auto pos = window.lower_bound(long(nums[i]) - t);//注意一定强制类型转换nums不然超int
cout << *pos << endl;
cout << nums[i]<<endl;
if (pos != window.end() && *pos - nums[i] <= t) return true; // 用*pos - nums[i] 不然 nums[i]+t超int
window.insert(nums[i]);
}
return false;
// for (int i = 0; i < nums.size() - k; i++) {
// for (int j = i + 1; j <= i + k; j++) {
// if (abs(nums[j] - nums[i]) <= t) return true;
// }
// }
// return false;
}
};
学习使用set,set的底层数据结构是BST,所有元素都是有序的,lower_bound(num)返回第一个>=num的iterator,upper_bound(num)返回第一个>num的iterator。