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

LeetCode-Contains Duplicate III

2015-10-11 11:39 435 查看
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) {
multiset<long long>bst;//set,multiset,map,multimap都是按照严格弱序保存的,所以插入一个元素不是简单的在末尾插入,它的插入有点类似二叉树。
for (int i = 0; i < nums.size(); ++i) {
if (bst.size() == k + 1) bst.erase(bst.find(nums[i - k - 1]));//如果执行到这里还没有找到符合条件的值,那么前面nums[0]-nums[i-k-1]都没                                                                                      //有存在的必要了。所以按照顺序,进一个删一个。nums[i-k-1]保证每次删除的                                                                                      //都是前k个元素的头元素。
auto lb = bst.lower_bound(nums[i]);
if (lb != bst.end() &&(abs(*lb - nums[i])<=t)) return true;//找到第一个大于等于它的数,后面就比它更大,所以nums[i]与bst后面的值无需比                                                                                   //较。
auto ub = bst.upper_bound(nums[i]);
if (ub != bst.begin() && abs(*(--ub) - nums[i]) <= t) return true;//考虑比它小的数的情况。
bst.insert(nums[i]);
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: