56. Merge Intervals
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了56. Merge Intervals相关的知识,希望对你有一定的参考价值。
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
以上是关于56. Merge Intervals的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 56. Merge Intervals