56. Merge Intervals
https://leetcode.com/problems/merge-intervals/
js
/**
* Definition for an interval.
* function Interval(start, end) {
* this.start = start;
* this.end = end;
* }
*/
/**
* @param {Interval[]} intervals
* @return {Interval[]}
*/
var merge = function(intervals) {
intervals.sort((a, b) => a.start - b.start)
var result = []
for (let interval of intervals) {
if (result.length === 0 || result[result.length - 1].end < interval.start) {
result.push(interval)
} else {
result[result.length - 1].end = Math.max(result[result.length - 1].end, interval.end)
}
}
return result
}
py
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key=lambda x: x.start)
result = []
for interval in intervals:
if not result or result[-1].end < interval.start:
result.append(interval)
else:
result[-1].end = max(result[-1].end, interval.end)
return result