forked from xhofe/daily-problem-of-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20-range-module.rs
70 lines (63 loc) · 1.74 KB
/
20-range-module.rs
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
// https://leetcode.cn/problems/range-module/
struct RangeModule {
map: std::collections::BTreeMap<i32, i32>,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl RangeModule {
fn new() -> Self {
Self {
map: std::collections::BTreeMap::new(),
}
}
fn add_range(&mut self, left: i32, right: i32) {
let mut removes = vec![];
let (mut L, mut R) = (left, right);
for (&r, &l) in self.map.range(left..) {
if l > right {
break;
}
removes.push(r);
L = L.min(l);
R = R.max(r);
}
for r in removes {
self.map.remove(&r);
}
self.map.insert(R, L);
}
fn query_range(&self, left: i32, right: i32) -> bool {
let (&r,&l) = self.map.range(left..).next().unwrap_or((&0, &0));
l <= left && right <= r
}
fn remove_range(&mut self, left: i32, right: i32) {
let mut removes = vec![];
let (mut L, mut R) = (right, left);
for (&r, &l) in self.map.range(left..) {
if l > right {
break;
}
removes.push(r);
L = L.min(l);
R = R.max(r);
}
for r in removes {
self.map.remove(&r);
}
if L < left {
self.map.insert(left, L);
}
if R > right {
self.map.insert(R, right);
}
}
}
/**
* Your RangeModule object will be instantiated and called as such:
* let obj = RangeModule::new();
* obj.add_range(left, right);
* let ret_2: bool = obj.query_range(left, right);
* obj.remove_range(left, right);
*/