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;
    };
    
    
  • 相关阅读:
    总结类初始化时的代码执行顺序
    Calcite数据源适配器对时间字段的操作问题
    如何自定义一个Calcite对Tablesaw查询的适配器
    Redis集群 Redis Cluster
    培养代码逻辑
    在线查看office文件的两种方法
    WPF Prism框架合集(9.Dialog)
    WPF Prism框架合集(8.Navigation)
    WPF Prism框架合集(7.Mvvm)
    springboot @OneToOne 解决JPA双向死循环/返回json数据死循环
  • 原文地址:https://www.cnblogs.com/charlesblc/p/6445718.html
Copyright © 2011-2022 走看看