zoukankan      html  css  js  c++  java
  • LeetCode-352 Data Stream as Disjoint Intervals

    题目描述

    Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.

    For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:

    [1, 1]
    [1, 1], [3, 3]
    [1, 1], [3, 3], [7, 7]
    [1, 3], [7, 7]
    [1, 3], [6, 7]

    题目大意

    将给定地一串正整数数字输入,整合成不相交的区间表示。

    示例

    如题目所示。

    解题思路

    LeetCode@Tiejun主要利用set<vector<int>>数据结构来表示不同的区间表示,每次插入新的数字时,遍历set查找可以合并的区间,并同时删除该区间,最后将整合好的区间插入set。

    复杂度分析

    时间复杂度:O(N)

    空间复杂度:O(N)

    代码

    class SummaryRanges {
    public:
        /** Initialize your data structure here. */
        SummaryRanges() {
            
        }
        
        void addNum(int val) {
            // 初始化新的区间,以新插入的数字为区间的中心点
            vector<int> merge = {val, val};
            // 遍历set,寻找可以合并的区间
            for (auto it = intervals.begin(); it != intervals.end();) {
                // 如果该区间不与新区间相连,则跳过
                if (it->front() - 1 > merge.back() || it->back() + 1 < merge.front())
                    ++it;
                // 否则将两个区间合并
                else {
                    merge.front() = min(it->front(), merge.front());
                    merge.back() = max(it->back(), merge.back());
                    it = intervals.erase(it);
                }
            }
            // 插入新区间
            intervals.insert(merge);
        }
        
        vector<vector<int>> getIntervals() {
            // 将set中的所有元素返回
            return vector<vector<int> >(intervals.begin(), intervals.end());
        }
        
    private:
        set<vector<int> > intervals;
    };
    
    /**
     * Your SummaryRanges object will be instantiated and called as such:
     * SummaryRanges* obj = new SummaryRanges();
     * obj->addNum(val);
     * vector<vector<int>> param_2 = obj->getIntervals();
     */
  • 相关阅读:
    Centos5.8 安装 ImageMagick 6.8.9-3
    Centos5.8 安装 Redmine
    Apache配置中的ProxyPass 和 ProxyPassReverse
    Centos5.8 安装SVN并配置HTTP访问
    Centos5.8 安装 MySQL5.6.19
    Centos5.8 安装 PHP5.5 和 memcached
    CentOS RHEL 安装 Tomcat 7
    Centos5.8 iptables管理
    在SecureCRT中使用rz和sz传输文件
    在Mac mini上安装 ESXi 5.5
  • 原文地址:https://www.cnblogs.com/heyn1/p/11232592.html
Copyright © 2011-2022 走看看