Contains Duplicate III

来源:互联网 发布:仿斗鱼直播源码 编辑:程序博客网 时间:2024/04/28 10:30

【题目描述】:

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.

【题目大意】:

给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k

【算法】
维护一个大小为 k 的二叉搜索树,来一个新的元素时,在BST上二分搜索有没有符合条件的数对,动态更新这个BST。因为BST的大小为 k 或不超过 k,所以这里面的数下标的差值一定是符合条件的。还有几点要注意的就是nums[i]与nums[j]的差值的是绝对值,所以要分别找lower_bound跟upper_bound,数据比较坑爹,为了防止溢出,容器用long long类型的。

【红黑树 set】
multiset 可以包含重复元素的set。与set操作类似。
重要函数:
const_iterator lower_bound(const Key& key):返回容器中大于等于key的迭代器指针
const_iterator upper_bound(const Key& key):返回容器中大于key的迭代器指针

【code】

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;    }};
0 0
原创粉丝点击