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

leetcode 220 Contains Duplicate III

2015-09-14 19:43 495 查看
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.

代码

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t)
{
if (!k || t<0 || nums.size()<2)
return false;
//使用了set可以排序,大小为k,滑动窗口浏览,看窗口内部有没有小于t的
//重复:就必然存在,不重复:就可以用set
set<int> record;
auto nLen = nums.size();
for (int i = 0; i < nLen;++i)
{
if (i>k)
record.erase(nums[i - k - 1]);     //两个相同时,早已return true
set<int>::iterator lower = record.lower_bound(nums[i] - t);
if (lower != record.end() && abs(nums[i] - *lower) <= t)
return true;

record.insert(nums[i]);
}
return false;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数组子序列查找