20240514 Finished

This commit is contained in:
jackfiled 2024-05-14 18:14:00 +08:00
parent b91240aeef
commit a503d481d4
2 changed files with 49 additions and 1 deletions

View File

@ -130,4 +130,5 @@ mod p49_group_anagrams;
mod p202_happy_number; mod p202_happy_number;
mod p219_contains_duplicate_ii; mod p219_contains_duplicate_ii;
mod p128_longest_consecutive_sequence; mod p128_longest_consecutive_sequence;
mod p228_summary_ranges; mod p228_summary_ranges;
mod p56_merge_intervals;

View File

@ -0,0 +1,47 @@
/**
* [56] Merge Intervals
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
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]])
)
}
}