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

[LeetCode] Contains Duplicate III

2015-06-01 15:33 369 查看

Contains Duplicate III

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.

一开始理解错题目了,还以为是要求所有的数对都必须符合要求,一直超时。其实题目是问是不是存在一个符合条件的数对,所以就容易多了,维护一个大小为 k 的二叉搜索树,来一个新的元素时,在BST上二分搜索有没有符合条件的数对,动态更新这个BST。因为BST的大小为 k 或不超过 k,所以这里面的数下标的差值一定是符合条件的。还有几点要注意的就是nums[i]与nums[j]的差值的是绝对值,所以要分别找lower_bound跟upper_bound,数据比较坑爹,为了防止溢出,容器用long long类型的。

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
multiset<long long> bst;
for (int i = 0; i < nums.size(); ++i) {
if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));
auto lb = bst.lower_bound(nums[i]);
if (lb != bst.end() && abs(*lb - nums[i]) <= t) return true;
auto ub = bst.upper_bound(nums[i]);
if (ub != bst.begin() && abs(*(--ub) - nums[i]) <= t) return true;
bst.insert(nums[i]);
}
return false;
}
};


不用比较两次,直接找nums[i] - t的lower_bound, 这个值就是与nums[i]差值最近的值。

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