# 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]
``````

What if there are lots of merges and the number of disjoint intervals are small compared to the data stream’s size?

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

Credits:
Special thanks to @yunhong for adding this problem and creating most of the test cases.

``````class SummaryRanges {
public:
SummaryRanges() {}

vector<int> newInterval{val, val};
vector<vector<int>> res;
int cur = 0;
for (auto interval : intervals) {
if (newInterval[1] + 1 < interval[0]) {
res.push_back(interval);
} else if (newInterval[0] > interval[1] + 1) {
res.push_back(interval);
++cur;
} else {
newInterval[0] = min(newInterval[0], interval[0]);
newInterval[1] = max(newInterval[1], interval[1]);
}
}
res.insert(res.begin() + cur, newInterval);
intervals = res;
}
vector<vector<int>> getIntervals() {
return intervals;
}
private:
vector<vector<int>> intervals;
};
``````

``````class SummaryRanges {
public:
SummaryRanges() {}

vector<int> newInterval{val, val};
int i = 0, overlap = 0, n = intervals.size();
for (; i < n; ++i) {
if (newInterval[1] + 1 < intervals[i][0]) break;
if (newInterval[0] <= intervals[i][1] + 1) {
newInterval[0] = min(newInterval[0], intervals[i][0]);
newInterval[1] = max(newInterval[1], intervals[i][1]);
++overlap;
}
}
if (overlap > 0) {
intervals.erase(intervals.begin() + i - overlap, intervals.begin() + i);
}
intervals.insert(intervals.begin() + i - overlap, newInterval);
}
vector<vector<int>> getIntervals() {
return intervals;
}
private:
vector<vector<int>> intervals;
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/352

Insert Interval

Range Module

Summary Ranges

https://leetcode.com/problems/data-stream-as-disjoint-intervals/

https://leetcode.com/problems/data-stream-as-disjoint-intervals/discuss/82557/Very-concise-c%2B%2B-solution.