问题描述
给你一个整数数组 nums 和两个整数 k 和 t 。请你判断是否存在 两个不同下标 i 和 j,使得 abs(nums[i] - nums[j]) <= t ,同时又满足 abs(i - j) <= k 。
如果存在则返回 true,不存在返回 false。
示例 1:
输入:nums = [1,2,3,1], k = 3, t = 0
输出:true
示例 2:
输入:nums = [1,0,1,1], k = 1, t = 2
输出:true
示例 3:
输入:nums = [1,5,9,1,5,9], k = 2, t = 3
输出:false
提示:
0 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 104
0 <= t <= 231 - 1
问题分析
对于序列中每一个元素 x 左侧的至多 k 个元素,如果这 k 个元素中存在一个元素落在区间 [x - t, x + t][x−t,x+t] 中,我们就找到了一对符合条件的元素。于是我们可以使用滑动窗口的思路,维护一个大小为 kk 的滑动窗口,每次遍历到元素 xx 时,滑动窗口中包含元素 xx 前面的最多 kk 个元素,我们检查窗口中是否存在元素落在区间 [x - t, x + t][x−t,x+t] 中即可。
代码献上
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int n=nums.size();
set<long> s;
for(int i=0; i<n; i++){
auto it=s.lower_bound((long)nums[i]-t);
if(it!=s.end() && *it<=t+(long)nums[i]){
return true;
}
s.insert(nums[i]);
if(i>=k){
s.erase(nums[i-k]);
}
}
return false;
}
};