From a503d481d49694e1715df134e38f45c18722fe40 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 14 May 2024 18:14:00 +0800 Subject: [PATCH] 20240514 Finished --- src/problem/mod.rs | 3 +- src/problem/p56_merge_intervals.rs | 47 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 src/problem/p56_merge_intervals.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 30785e6..047020a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -130,4 +130,5 @@ mod p49_group_anagrams; mod p202_happy_number; mod p219_contains_duplicate_ii; mod p128_longest_consecutive_sequence; -mod p228_summary_ranges; \ No newline at end of file +mod p228_summary_ranges; +mod p56_merge_intervals; \ No newline at end of file diff --git a/src/problem/p56_merge_intervals.rs b/src/problem/p56_merge_intervals.rs new file mode 100644 index 0000000..026be90 --- /dev/null +++ b/src/problem/p56_merge_intervals.rs @@ -0,0 +1,47 @@ +/** + * [56] Merge Intervals + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn merge(intervals: Vec>) -> Vec> { + let mut intervals: Vec<(i32, i32)> = intervals.iter().map(|p| (p[0], p[1])).collect(); + + intervals.sort_unstable(); + + let mut result: Vec<(i32, i32)> = vec![intervals[0]]; + let mut last = 0; + + for i in 1..intervals.len() { + let (begin, end) = intervals[i]; + let (last_begin, last_end) = result[last]; + + if begin <= last_end { + result[last].0 = result[last].0.min(begin); + result[last].1 = result[last].1.max(end); + } else { + result.push(intervals[i]); + last += 1; + } + } + + result.iter().map(|p| vec![p.0, p.1]).collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_56() { + assert_eq!( + vec![vec![1, 6], vec![8, 10], vec![15, 18]], + Solution::merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]) + ) + } +}