题目
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.
题意
给定一个整型数组,查找是否存在两个元素nums[i],nums[j]使得,|nums[i]-nums[j]|<= t,并且j-i<= k
注意
- 相对于Contains Duplicate II 增加了条件|nums[i]-nums[j]|<= t。
- nums[i]-t <= nums[j] <= nums[i]+t
- 当我们拆开这个绝对值符合当心整型越界
思路
由于我们的窗口范围仍然是j-i<= k,我们可以复用Contains Duplicate II
ceil(v-t) —— >= v-t—————-ceil(v-t) <= v+t即可
floor(v+t) ——- <=v+t————–v-t <= floor(v+t)即可
STL中为我们提供了ceil的实现lower_bound
使用lower_bound,需要利用红黑树实现的map,因为这样的键是有序的
代码
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> record;
for (int r = 0; r < nums.size(); r++)
{
//负数
//abs(i-j) <= t i-t << j <<i+t
if(record.lower_bound((long long)nums[r]-t) != record.end()&&*record.lower_bound((long long)nums[r]-t) <= ((long long )nums[r]+t))
return true;
//record[nums[r]]++;
record.insert(nums[r]); //set集合不可像map那样插入元素
//保持record中最多有k个元素 [0,K]区间中有k+1个元素
if (record.size() == k + 1)
record.erase(nums[r - k]);
}
return false;
}
};
map迭代器的使用注意,解引用时需要括号,因为.的优先级高于*