Skip to content

Commit 5c51b9c

Browse files
committed
feat(intervals): add 56_merge_intervals.rs
1 parent b56b11e commit 5c51b9c

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,3 +160,9 @@ so that you can use `just tf TEST` command to test.
160160
| - | - | - |
161161
| 703. Kth Largest Element in a Stream | Easy | [703_kth_largest_element_in_a_stream.rs](./tests/703_kth_largest_element_in_a_stream.rs) |
162162
| 1046. Last Stone Weight | Easy | [1046_last_stone_weight.rs](./tests/1046_last_stone_weight.rs) |
163+
164+
### Intervals
165+
166+
| Problem | Difficulty | Solution |
167+
| - | - | - |
168+
| 56. Merge Intervals | Medium | [56_merge_intervals.rs](./tests/56_merge_intervals.rs) |

tests/56_merge_intervals.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// 56. Merge Intervals
2+
// https://leetcode.com/problems/merge-intervals/description/
3+
// Topics: Intervals.
4+
// Difficulty: Medium.
5+
6+
#[test]
7+
fn test_56_merge_intervals() {}
8+
9+
#[derive(Debug)]
10+
pub struct Solution;
11+
12+
// ---------------------------------
13+
// copy to leetcode starts from here
14+
// ---------------------------------
15+
16+
impl Solution {
17+
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
18+
use std::collections::BinaryHeap;
19+
let mut heap: BinaryHeap<StartEnd> = BinaryHeap::new();
20+
for item in intervals.iter() {
21+
heap.push(StartEnd {
22+
start: *item.first().unwrap(),
23+
end: *item.last().unwrap(),
24+
});
25+
}
26+
let mut result: Vec<Vec<i32>> = vec![];
27+
while !heap.is_empty() {
28+
// heap is not empty, thus unwrap() is safe.
29+
let bigger_end = heap.pop().unwrap();
30+
let Some(smaller_end) = heap.peek() else {
31+
result.push(bigger_end.into());
32+
break;
33+
};
34+
// if no overlap
35+
if smaller_end.end < bigger_end.start {
36+
result.push(bigger_end.into());
37+
} else {
38+
let new_item = StartEnd {
39+
start: std::cmp::min(smaller_end.start, bigger_end.start),
40+
end: bigger_end.end,
41+
};
42+
heap.pop();
43+
heap.push(new_item);
44+
}
45+
}
46+
result
47+
}
48+
}
49+
50+
#[derive(Eq)]
51+
struct StartEnd {
52+
start: i32,
53+
end: i32,
54+
}
55+
56+
impl From<StartEnd> for Vec<i32> {
57+
fn from(val: StartEnd) -> Self {
58+
vec![val.start, val.end]
59+
}
60+
}
61+
62+
impl PartialEq for StartEnd {
63+
fn eq(&self, other: &Self) -> bool {
64+
self.end == other.end
65+
}
66+
}
67+
68+
impl PartialOrd for StartEnd {
69+
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
70+
Some(self.cmp(other))
71+
}
72+
}
73+
74+
impl Ord for StartEnd {
75+
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
76+
self.end.cmp(&other.end)
77+
}
78+
}

0 commit comments

Comments
 (0)