LandscapeMi

landscapemi的博客

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

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;
    }
};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52385128
个人分类: leetcode(c++)
上一篇leetcode:Brainteaser: Nim Game(292)
下一篇leetcode:Data Stream as Disjoint Intervals(352)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭