# Merge Intervals in Rust

impl Solution {
pub fn merge(mut intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
// Check if the input is empty
if intervals.is_empty() {
return vec![];
}

// Sort the intervals based on the start of each interval
intervals.sort_by(|a, b| a[0].cmp(&b[0]));

let mut merged: Vec<Vec<i32>> = Vec::new();

for interval in intervals.iter() {
// If merged is empty or the current interval does not overlap with the last one in merged
if merged.is_empty() || merged.last().unwrap()[1] < interval[0] {
merged.push(interval.clone());
} else {
// If there is an overlap, merge the current interval with the last one in merged
let last = merged.last_mut().unwrap();
last[1] = i32::max(last[1], interval[1]);
}
}

merged
}
}

impl Solution {
pub fn merge(mut intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
// Check if the input is empty
if intervals.is_empty() {
return vec![];
}

// Convert the intervals to a Vec of tuples for easier manipulation
let mut intervals: Vec<(i32, i32)> = intervals.into_iter().map(|v| (v[0], v[1])).collect();

// Sort the intervals based on the start of each interval
intervals.sort_by(|a, b| a.0.cmp(&b.0));

let mut merged: Vec<(i32, i32)> = Vec::new();

for interval in intervals.iter() {
// If merged is empty or the current interval does not overlap with the last one in merged
if merged.is_empty() || merged.last().unwrap().1 < interval.0 {
merged.push(*interval);
} else {
// If there is an overlap, merge the current interval with the last one in merged
let last = merged.last_mut().unwrap();
last.1 = i32::max(last.1, interval.1);
}
}

// Convert the merged intervals back to Vec<Vec<i32>>
merged
.into_iter()
.map(|(start, end)| vec![start, end])
.collect()
}
}