56. Merge Intervals
https://leetcode.com/problems/merge-intervals/
Python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) < 2:
return intervals
intervals.sort(key=lambda pair: pair[0])
result = []
start, end = intervals[0]
for i in range(len(intervals)):
if intervals[i][0] <= end:
end = max(end, intervals[i][1])
continue
result.append([start, end])
start, end = intervals[i]
result.append([start, end])
return result
Rust
use std::cmp::max;
impl Solution {
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
if intervals.len() < 2 {
return intervals;
}
let mut sorted_intervals = intervals.clone();
sorted_intervals.sort_by_key(|pair| pair[0]);
let mut result = vec![];
let mut start = sorted_intervals[0][0];
let mut end = sorted_intervals[0][1];
for i in 0..sorted_intervals.len() {
if sorted_intervals[i as usize][0] <= end {
end = max(end, sorted_intervals[i as usize][1]);
continue
}
result.push(vec![start, end]);
start = sorted_intervals[i as usize][0];
end = sorted_intervals[i as usize][1];
}
result.push(vec![start, end]);
result
}
}