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] andnums[j] is
at most t and the difference
between i and j is
at most k.
一开始以为和前两道差不多,做了之后发现不太一样,如果用前两道题的方法,一般都会超时,即使判断t和k大小分别用不同的方式还是超时。
所以采用滑动窗口,保证map里面的所有key下标只差在k以内,然后找一个和nums[i]差值在t以内的值。
lower_bound(x)和upper_bound的区别:
lower_bound(x)返回一个key>=x的iterator
upper_bound(x)返回一个key>x的iterator
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
map<int, int> mp;
int j = 0;
map<int, int>::iterator it = mp.end();
for(int i = 0; i < nums.size(); i++){
if(i - j > k) mp.erase(nums[j++]);
it = mp.lower_bound(nums[i]-t);
if(it != mp.end() && it->first - nums[i] <= t)return true;
mp[nums[i]] = i;
}
return false;
}
};

本文探讨了一种使用滑动窗口与映射表解决数组中寻找特定条件下的相似元素问题的方法。通过确保映射表内键的索引差不超过预设值k,并查找与当前元素差值不超过t的值,有效解决了此问题。文章提供了详细的C++实现代码。
1721

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



