LeetCode题解——Data Stream as Disjoint Intervals

来源:互联网 发布:网络推广优化 编辑:程序博客网 时间:2024/06/07 16:39

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]


struct Interval {     int start;     int end;     Interval() : start(0), end(0) {}     Interval(int s, int e) : start(s), end(e) {} }; 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;};

0 0
原创粉丝点击