leetcode:Binary Search Tree:Contains Duplicate III(220)

来源:互联网 发布:编程时间和水平成正比 编辑:程序博客网 时间:2024/06/06 07:35

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