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

leetcode.220. Contains Duplicate III

2016-05-10 23:12 651 查看
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.

问题描述:判断数组中是否存在<ai aj> abs(ai - aj)<=t && abs(i - j) <=k;

问题分析:需要一个数据结构来维护满足条件k。单纯暴力,会超时。假设当前元素num[i]我只需要判断 i- k -1 到 i之间的元素的关系就可以了。假设当前元素是num[i], 另一个元素a(multiset中的),他们满足| a - num[i]|<=t   可得到   num[i] - t <= a <= num[i] + t。所以我需要尽快找到 num[i] - t 的下界(lb)(第一个大于等于 num[i] - t的值)然后在判断 |lb - num[i]| <= t是否满足 。

问题解决:这里使用multiset来维护最多k个元素。区别与set , multiset可以存储多个相同的元素。然后按照升序关系排列。

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);//第一个大于等num[i]的元素位置
if (lb != bst.end() && *lb - nums[i] <= t) return true;
bst.insert(nums[i]);
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: