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,找出是否存在:两个不同的下标(索引index)i 和 j ,使得nums[i] 和 nums[j]的差的绝对值小于等于t,i 和 j 的差的绝对值小于等于k。
思路:建立一个set数据类型,把 i 之前k个数存入set中,set默认数据是从小到大排序的。
对于i,j 时,若符合条件,则有 | nums[j] - nums[i] |<=t,则-t <= nums[j] - nums[i] <= t,因此有nums[j]>=num[i] - t,因此使用lower_bound函数获取set中大于等于num[i] - t的第一个元素,若存在该元素(it!=s.end()),则再判断 nums[j] - nums[i] <= t是否成立,需要注意的是整数可能溢出。
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<int> s;
for(int i=0;i<nums.size();i++)
{
//if(s.size()==k) s.erase(nums[i-k]);//错误!
if(i-k-1>=0) s.erase(nums[i-k-1]);//当i>k+1时,就一直删除最先存入set里面的数
auto it = s.lower_bound(nums[i]-t);
if(it!=s.end()&&((long)*it-(long)nums[i])<=t) return true;
s.insert(nums[i]);
}
return false;
}
};
浙公网安备 33010602011771号