Bernini @ buffalo

ME转CS,蛋疼菊紧中.........

leecode_220 Contains Duplicate III

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.

两月没刷没手感了, nk的复杂度解法超时,

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        int len=nums.size();
        if (len<=1 || k==0 )
            return false;
            
        multiset<int> tree;
        
        for (int i=0;i<nums.size();i++){
            if (tree.size()>k)
                  tree.erase(nums[i-k-1]);
            if (tree.size()>0){
                 multiset<int>::iterator low_bound=tree.lower_bound(nums[i]-abs(t));//返回>=nums[i]-abs(t)的第一个值;
                 multiset<int>::iterator up_bound=tree.lower_bound(nums[i]);//返回>nums[i]的第一个值;
                 
                 if (low_bound!=tree.end() && abs(*low_bound-nums[i])<=t)
                     return true;
                 if (up_bound!=tree.end() && abs(*up_bound-nums[i])<=t)
                    return true;
            }
            tree.insert(nums[i]);
        }
        
        
        return false;
        
        
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31552435/article/details/51565105
个人分类: LeeCode
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭