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.
代码
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t)
{
if (!k || t<0 || nums.size()<2)
return false;
//使用了set可以排序,大小为k,滑动窗口浏览,看窗口内部有没有小于t的
//重复:就必然存在,不重复:就可以用set
set<int> record;
auto nLen = nums.size();
for (int i = 0; i < nLen;++i)
{
if (i>k)
record.erase(nums[i - k - 1]); //两个相同时,早已return true
set<int>::iterator lower = record.lower_bound(nums[i] - t);
if (lower != record.end() && abs(nums[i] - *lower) <= t)
return true;
record.insert(nums[i]);
}
return false;
}
};
本文介绍了一种算法,用于判断一个整数数组中是否存在两个不同的索引i和j,使得nums[i]与nums[j]之差的绝对值不超过t,且i与j之差不超过k。通过使用滑动窗口和集合来实现高效查找。
9032

被折叠的 条评论
为什么被折叠?



