-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path352.cpp
98 lines (87 loc) · 2.47 KB
/
352.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class SummaryRanges {
public:
map<int, int> intervals;
SummaryRanges() {
}
void addNum(int val) {
int left = val;
int right = val;
auto hi = intervals.upper_bound(val); // >
auto lo = intervals.lower_bound(val); // >=
// if lower bound cover val => return
if (lo != intervals.end() && lo->first == val) return;
// move back
if (lo != intervals.begin()) {
lo--;
// if the previous one's end >= val: return
if (lo != intervals.end() && lo->second >= val) return;
}
// merge left
if (lo != intervals.end() && lo->second == val - 1) {
left = min(left, lo->first);
intervals.erase(lo);
}
// merge right
if (hi != intervals.end() && hi->first == val + 1) {
right = max(right, hi->second);
intervals.erase(hi);
}
intervals[left] = right;
}
vector<vector<int>> getIntervals() {
vector<vector<int>> res;
for (auto [l, r] : intervals) {
res.push_back({l, r});
}
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();
*/
// v2
class SummaryRanges {
public:
map<int, int> mp;
SummaryRanges() {
}
void addNum(int value) {
int left = value;
int right = value;
auto it = mp.upper_bound(value); // >
auto itL = it;
// deal with the left bound
if (it != mp.begin()) {
itL--;
if (itL->second >= value - 1) {
if (itL->second >= right) return;
left = itL->first;
mp.erase(itL);
}
}
// deal with the right bound
if (it != mp.end()) {
if (it->first <= value + 1) {
right = it->second;
mp.erase(it);
}
}
mp[left] = right;
}
vector<vector<int>> getIntervals() {
vector<vector<int>> res;
for (auto& [l, r] : mp) {
res.push_back({l ,r});
}
return res;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(value);
* vector<vector<int>> param_2 = obj->getIntervals();
*/