[LeetCode] Data Stream as Disjoint Intervals

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.

Implement the SummaryRanges class:

  • SummaryRanges() Initializes the object with an empty stream.
  • void addNum(int val) Adds the integer val to the stream.
  • int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi].
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class SummaryRanges {
map<int, int> range;
public:
SummaryRanges() {}

void addNum(int val) {
if(range.empty()) {
range[val] = val;
return;
}
auto lower = range.lower_bound(val);
if(lower->first == val) return;
if(lower != begin(range)) {
auto prv = prev(lower);
if(prv->second >= val) return;
else if(prv->second == val - 1) {
prv->second = val;
if(lower->first == val + 1) {
prv->second = lower->second;
range.erase(lower);
}
return;
}
}
if(lower != end(range)) {
if(lower->first == val + 1) {
range[val] = lower->second;
range.erase(lower);
return;
} else {
range[val] = val;
}
} else {
range[val] = val;
}
}

vector<vector<int>> getIntervals() {
vector<vector<int>> res;
for(auto [f, t] : range) {
res.push_back({f,t});
}
return res;
}
};

/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector<vector<int>> param_2 = obj->getIntervals();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/04/PS/LeetCode/data-stream-as-disjoint-intervals/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.