We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8771fb8 commit d128b77Copy full SHA for d128b77
merge-intervals/yhkee0404.rs
@@ -0,0 +1,21 @@
1
+use itertools::Itertools;
2
+use std::cmp::max;
3
+
4
+impl Solution {
5
+ pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
6
+ let mut intervals: Vec<_> = intervals.iter()
7
+ .cloned()
8
+ .sorted_by(|a, b| a.cmp(b)) // T(n) = O(nlogn)
9
+ .collect();
10
+ let mut ans: Vec<Vec<i32>> = vec![];
11
+ let mut end = -1;
12
+ for interval in intervals {
13
+ if ans.is_empty() || ans.last().unwrap()[1] < interval[0] {
14
+ ans.push(interval) // S(n) = O(n)
15
+ } else {
16
+ ans.last_mut().unwrap()[1] = max(ans.last().unwrap()[1], interval[1])
17
+ }
18
19
+ ans
20
21
+}
0 commit comments