-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0352-data-stream-as-disjoint-intervals.rs
73 lines (60 loc) · 1.5 KB
/
0352-data-stream-as-disjoint-intervals.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
71
72
73
// BTreeSet Solution
use std::collections::BTreeSet;
struct SummaryRanges {
tree_map: BTreeSet<i32>,
}
impl SummaryRanges {
fn new() -> Self {
Self {
tree_map: BTreeSet::new(),
}
}
fn add_num(&mut self, value: i32) {
self.tree_map.insert(value);
}
fn get_intervals(&self) -> Vec<Vec<i32>> {
let mut res: Vec<Vec<i32>> = vec![];
for n in &self.tree_map {
if !res.is_empty() && res.last().unwrap()[1] + 1 == *n {
let mut last = res.pop().unwrap();
last[1] = *n;
res.push(last);
} else {
res.push(vec![*n, *n]);
}
}
res
}
}
// HashSet Solution
use std::collections::HashSet;
struct SummaryRanges {
ranges: Vec<Vec<i32>>,
num_set: HashSet<i32>,
}
impl SummaryRanges {
fn new() -> Self {
Self {
ranges: vec![],
num_set: HashSet::new(),
}
}
fn add_num(&mut self, value: i32) {
self.num_set.insert(value);
}
fn get_intervals(&self) -> Vec<Vec<i32>> {
let mut nums: Vec<i32> = self.num_set.iter().cloned().collect();
nums.sort();
let mut res = vec![];
let mut i = 0;
while i < nums.len() {
let start = nums[i];
while i + 1 < nums.len() && nums[i] + 1 == nums[i + 1] {
i += 1;
}
res.push(vec![start, nums[i]]);
i += 1;
}
res
}
}