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.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3 Output: false
解题思路:
1、创建set。(set内的元素为升序排序且唯一)
2、设置大小为k的滑动窗口,判断nums[i]与滑动窗口中各值的绝对差是否小于t。
参考https://blog.youkuaiyun.com/lv1224/article/details/76627279
如复制到vector<long long>中超时。
lower_bound(key_value) ,返回第一个大于等于key_value的定位器
upper_bound(key_value),返回最后一个大于key_value的定位器
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> s; //long long避免
for(int i=0,j=0;i<nums.size();i++)
{
if(i-j>k)
{
s.erase(nums[j]);
j++;
}
auto it=s.lower_bound((long long)nums[i]-t); //找到第一个大于等于nums[i]-t的,即左界限
if(it!=s.end()&&abs(nums[i]-*it)<=t) //找到,且判断是否小于等于右界限
{
return true;
}
s.insert(nums[i]);
}
return false;
}
};
LeetCode217. Contains Duplicate [C++]
LeetCode219. Contains DuplicateII [C++]