您的位置:首页 > 大数据 > 人工智能

220. Contains Duplicate III

2016-03-15 17:11 369 查看
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] and nums[j] is at most t and the difference between i and j is at most k.

解法:
这里的 t,k 均是大于0的,
用 set 保存当前位置前边的k个位置的数据,A: nums[i]
set 中的某个数据可用x表示。这里选用set的原因是 下边会用到求下界操作
则当满足下式时返回true
|x-A|<=t
-t<=x-A<=t
观察左半边:-t<=x-A,则满足条件的x>=A-t,即需要查找set中是否有大于或者等于(A-t)的数,如果有,则进行下一步判断。否则继续往后扫描数组。
如果set中有这样A-t的下界存在,假定这个数为X,
则满足:X-A<=t 时返回true
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int size=nums.size();
if(size<=1||k<=0)
return false;

set<int> table;
for(int i=0;i<size;++i){
if(i>k){
table.erase(nums[i-k-1]);
}
auto it=table.lower_bound(nums[i]-t);
if(it!=table.end()&&*it-nums[i]<=t)
return true;
table.insert(nums[i]);
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: