• 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;
    };
    
    
  • 相关阅读:
    P1219 N皇后(位运算&普通dfs)
    P1434 滑雪(记忆化搜索)
    P1118 数字三角形(技巧)
    P1162 填涂颜色
    P1141 01迷宫
    P2685抓牛(bfs)
    WordPress ‘crypt_private()’方法远程拒绝服务漏洞
    java获取网页源码
    tomcat报错: Error parsing HTTP request header
    空指针异常的原因
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6445718.html
Copyright © 2020-2023  润新知