首页 > 代码库 > 56. Merge Intervals
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。