zoukankan      html  css  js  c++  java
  • Java的TreeMap,C++的lower_bound,合并间隔

    https://leetcode.com/problems/data-stream-as-disjoint-intervals/?tab=Description

    这道题目是合并间隔的经典题目。

    https://discuss.leetcode.com/topic/46887/java-solution-using-treemap-real-o-logn-per-adding/2

    这里里面有用了Java的TreeMap,可以方便的 

    Integer l = tree.lowerKey(val);
    Integer h = tree.higherKey(val);

    而下面用到了C++的lower_bound,起到了相同的二分查找的作用:

    https://discuss.leetcode.com/topic/46904/very-concise-c-solution/2

    class SummaryRanges {
    public:
        /** Initialize your data structure here. */
        void addNum(int val) {
            auto it = st.lower_bound(Interval(val, val));
            int start = val, end = val;
            if(it != st.begin() && (--it)->end+1 < val) it++;
            while(it != st.end() && val+1 >= it->start && val-1 <= it->end)
            {
                start = min(start, it->start);
                end = max(end, it->end);
                it = st.erase(it);
            }
            st.insert(it,Interval(start, end));
        }
        
        vector<Interval> getIntervals() {
            vector<Interval> result;
            for(auto val: st) result.push_back(val);
            return result;
        }
    private:
        struct Cmp{
            bool operator()(Interval a, Interval b){ return a.start < b.start; }
        };
        set<Interval, Cmp> st;
    };

    而实际上,第一种解法,可以方便的使用C++ STL里面的lower_bound函数,来直接实现vector里面的二分查找。

    auto it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp);
    class SummaryRanges {
    public:
        void addNum(int val) {
            auto Cmp = [](Interval a, Interval b) { return a.start < b.start; };
            auto it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp);
            int start = val, end = val;
            if(it != vec.begin() && (it-1)->end+1 >= val) it--;
            while(it != vec.end() && val+1 >= it->start && val-1 <= it->end)
            {
                start = min(start, it->start);
                end = max(end, it->end);
                it = vec.erase(it);
            }
            vec.insert(it,Interval(start, end));
        }
        
        vector<Interval> getIntervals() {
            return vec;
        }
    private:
        vector<Interval> vec;
    };
    
    
  • 相关阅读:
    支付宝沙箱环境应用
    七牛云视频托管
    腾讯云短息验证码接口
    git远程连接(码云)
    git
    字间距
    html文本保留空格
    mysql重启导致AUTO_INCREMENT从1开始
    js保留两位小数
    vue中watch的基本用法
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6445718.html
Copyright © 2011-2022 走看看