forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
range-module.cpp
84 lines (76 loc) · 2.61 KB
/
range-module.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
// Time: addRange: O(n)
// removeRange: O(n)
// queryRange: O(logn)
// Space: O(n)
class RangeModule {
public:
RangeModule() {
}
// Time: O(n)
void addRange(int left, int right) {
vector<pair<int, int>> tmp;
int i = 0;
for (const auto& interval: intervals_) {
if (right < interval.first ) {
tmp.emplace_back(left, right);
break;
} else if (interval.second < left) {
tmp.emplace_back(interval);
} else {
left = min(left, interval.first);
right = max(right, interval.second);
}
++i;
}
if (i == intervals_.size()) {
tmp.emplace_back(left, right);
}
while (i < intervals_.size()) {
tmp.emplace_back(intervals_[i++]);
}
swap(intervals_, tmp);
}
// Time: O(logn)
bool queryRange(int left, int right) {
const auto it = lower_bound(intervals_.begin(), intervals_.end(), make_pair(left, right),
[](const pair<int, int>& lhs,
const pair<int, int>& rhs) {
return less<int>{}(lhs.second, rhs.first);
});
return it != intervals_.end() && it->first <= left && it->second >= right;
}
// Time: O(logn)
bool queryRange2(int left, int right) {
auto it = lower_bound(intervals_.begin(), intervals_.end(), make_pair(left, numeric_limits<int>::max()));
if (it != intervals_.begin()) {
it = prev(it);
}
return it != intervals_.end() && it->first <= left && it->second >= right;
}
// Time: O(n)
void removeRange(int left, int right) {
vector<pair<int, int>> tmp;
for (const auto& interval : intervals_) {
if (interval.second <= left || interval.first >= right) {
tmp.emplace_back(interval);
} else {
if (interval.first < left) {
tmp.emplace_back(interval.first, left);
}
if (right < interval.second) {
tmp.emplace_back(right, interval.second);
}
}
}
swap(intervals_, tmp);
}
private:
vector<pair<int, int>> intervals_;
};
/**
* Your RangeModule object will be instantiated and called as such:
* RangeModule obj = new RangeModule();
* obj.addRange(left,right);
* bool param_2 = obj.queryRange(left,right);
* obj.removeRange(left,right);
*/