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].
Subscribe to see which companies asked this question
# 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):
l = []
for i in intervals:
l += [i.start,i.end],
l.sort()
res = []
i = 0
while i < (len(l)):
s = l[i][0]
e = l[i][1]
while i < len(l)-1 and l[i+1][0] <= e:
e = max(l[i+1][1],e)
i += 1
res += Interval(s,e),
i += 1
return res
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""

本文介绍了一种有效的算法来合并一系列可能存在重叠的区间。通过示例说明了如何将输入的区间列表 [1,3],[2,6],[8,10],[15,18] 合并为 [1,6],[8,10],[15,18]。该算法首先将所有区间端点排序,然后遍历这些端点来合并重叠的区间。
1万+

被折叠的 条评论
为什么被折叠?



