From 25ed407f1744f34f5fc0a21a86c42dc567c83e54 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Wed, 15 May 2024 14:23:43 +0800 Subject: [PATCH] 20240515 Finished --- src/problem/mod.rs | 3 +- src/problem/p57_insert_interval.rs | 49 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/problem/p57_insert_interval.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 047020a..92bd317 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -131,4 +131,5 @@ mod p202_happy_number; mod p219_contains_duplicate_ii; mod p128_longest_consecutive_sequence; mod p228_summary_ranges; -mod p56_merge_intervals; \ No newline at end of file +mod p56_merge_intervals; +mod p57_insert_interval; \ No newline at end of file diff --git a/src/problem/p57_insert_interval.rs b/src/problem/p57_insert_interval.rs new file mode 100644 index 0000000..859ad40 --- /dev/null +++ b/src/problem/p57_insert_interval.rs @@ -0,0 +1,49 @@ +/** + * [57] Insert Interval + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn insert(intervals: Vec>, new_interval: Vec) -> Vec> { + let (mut left, mut right) = (new_interval[0], new_interval[1]); + + let mut result = vec![]; + let mut placed = false; + + for interval in intervals { + if interval[1] < left { + result.push(interval); + } else if interval[0] > right { + if !placed { + result.push(vec![left, right]); + placed = true; + } + + result.push(interval); + } else { + left = left.min(interval[0]); + right = right.max(interval[1]); + } + } + + if !placed { + result.push(vec![left, right]); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_57() { + } +}