https://leetcode.com/problems/merge-intervals/#/solutions
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
Sol:
Sort intervals according to their start time.
Create a new list and append intervals into it. Always compare the start time of the yet-to-add interval to the end time of the last element in the result. ....
# 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] """ # Just go through the intervals sorted by start coordinate and either combine the current interval with the previous one if they overlap, or add it to the output by itself if they don't. res = [] for interval in sorted(intervals, key = lambda i : i.start): if res and interval.start <= res[-1].end: res[-1].end = max(res[-1].end, interval.end) else: res.append(interval) return res