给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]] 输出: [[1,6],[8,10],[15,18]] 解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: [[1,4],[4,5]] 输出: [[1,5]] 解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
渣渣晴写的太蠢了
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
i=0
while i<len(intervals)-1:
j=i+1
while j<len(intervals):
if intervals[i].start<=intervals[j].start and intervals[i].end>=intervals[j].end:#i包括j
del intervals[j]
elif intervals[j].start<=intervals[i].start and intervals[j].end>=intervals[i].end:#j包括i
intervals[i].end=intervals[j].end
intervals[i].start=intervals[j].start
del intervals[j]
j=i+1
elif intervals[i].end>=intervals[j].start and intervals[i].start<=intervals[j].end and intervals[i].start<=intervals[j].start:#i尾j头拼接
intervals[i].end=intervals[j].end
del intervals[j]
j=i+1
elif intervals[j].end>=intervals[i].start and intervals[j].start<=intervals[i].end and intervals[j].start<=intervals[i].start:#j尾i头拼接
intervals[i].start=intervals[j].start
del intervals[j]
j=i+1
else:
j=j+1
i=i+1
return intervals
大佬的代码:
先按start排个序……再看看能不能合并……
class Solution:
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
intervals.sort(key=lambda x :x.start)
result = []
for item in intervals:
if not result or result[-1].end < item.start:
result.append(item)
else:
result[-1].end = max(item.end, result[-1].end)
# print(result)
return result