[LeetCode] Data Stream as Disjoint Intervals 分離區間的資料流
阿新 • • 發佈:2018-12-27
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]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
Credits:
Special thanks to @yunhong for adding this problem and creating most of the test cases.
這道題說有個資料流每次提供一個數字,然後讓我們組成一系列分離的區間,這道題跟之前那道Insert Interval很像,思路也很像,每進來一個新的數字val,我們都生成一個新的區間[val, val],然後將其插入到當前的區間裡,注意分情況討論,無重疊,相鄰,和有重疊分開討論處理,參見程式碼如下:
class SummaryRanges { public: /** Initialize your data structure here. */ SummaryRanges() {} void addNum(int val) { Interval cur(val, val); vector<Interval> res; int pos = 0; for (auto a : v) { if (cur.end + 1 < a.start) { res.push_back(a); }else if (cur.start > a.end + 1) { res.push_back(a); ++pos; } else { cur.start = min(cur.start, a.start); cur.end = max(cur.end, a.end); } } res.insert(res.begin() + pos, cur); v = res; } vector<Interval> getIntervals() { return v; } private: vector<Interval> v; };
類似題目:
參考資料: