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;
};

 

 


posted @ 2017-02-26 20:25  blcblc  阅读(1305)  评论(0编辑  收藏  举报