-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28_datastreamasdisjointinterval.cpp
More file actions
62 lines (55 loc) · 1.75 KB
/
28_datastreamasdisjointinterval.cpp
File metadata and controls
62 lines (55 loc) · 1.75 KB
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
53
54
55
56
57
58
59
60
61
62
//https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/
class SummaryRanges {
public:
SummaryRanges() {
}
void addNum(int value) {
auto it = _map.lower_bound(value);
bool merged = false;
if(it != _map.begin()) {
auto prev = it;
--prev;
if(prev->second + 1 >= value) {
merged = true;
prev->second = max(prev->second, value);
}
}
if(it != _map.end()) {
if(it->first - 1 <= value) {
if(merged) {
auto prev = it;
--prev;
if(prev->second >= it->first - 1) {
prev->second = max(prev->second, it->second);
_map.erase(it);
}
} else {
merged = true;
if(it->first != value) {
pair<int, int> p = *it;
p.first = min(p.first, value);
it = _map.insert(it, p);
++it;
if(it != _map.end())
_map.erase(it);
}
}
}
}
if(!merged)
_map.insert(it, {value, value});
}
vector<vector<int>> getIntervals() {
vector<vector<int>> intervals;
for(auto const & p : _map)
intervals.push_back({p.first, p.second});
return intervals;
}
map<int, int> _map;
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(value);
* vector<vector<int>> param_2 = obj->getIntervals();
*/