【LeetCode】220. Contains Duplicate III

时间:2023-03-09 04:16:13
【LeetCode】220. Contains Duplicate III

题目:

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.

提示:

看到题目之后,马上想到了题目应该是要利用一个长度为k的划窗,那么问题就在于用什么数据结构来构造这个划窗。由于当新的数字进来后,我们需要比较它和划窗内其他数字的大小关系,从搜索的效率角度出发,可以使用BST,因此我们选择STL中的SET容器来构造这个划窗。

思路也很简单,当新进来一个数后,先在容器中寻找是否有比nums[i]-t大的数字,这一步可以利用lower_bound函数实现,之后再比较比nums[i]-t大的数字中最小的那个与nums[i]的差,如果符合条件就返回true。

另外不要忘记划窗移动时,删除和插入相应的元素。

代码:

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (k < ) {
return false;
}
set<int> window;
for (int i = ; i < nums.size(); ++i) {
if (i > k) {
window.erase(nums[i-k-]);
}
auto pos = window.lower_bound(nums[i] - t);
if (pos != window.end() && *pos - nums[i] <= t) {
return true;
}
window.insert(nums[i]);
}
return false;
}
};