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.
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t)
{
if (!k || t<0 || nums.size()<2)
return false;
set<int>record;
auto nLen = nums.size();
for (int i = 0; i < nLen;++i)
{
if (i>k)
record.erase(nums[i - k - 1]);
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;
}
本文介绍了一种算法,用于判断一个整数数组中是否存在两个不同的元素,这两个元素的索引之差不超过k,且数值之差不超过t。通过使用滑动窗口结合有序集合的方法,可以在O(n log n)的时间复杂度内解决此问题。
669

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



