跳到主要内容

Merge Intervals

描述

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]

分析

复用一下 Insert Intervals 的解法即可,创建一个新的 interval 集合,然后每次从旧的里面取一个 interval 出来,然后插入到新的集合中。

代码

# Merge Interval
# Reuse solution from Insert Intervals
# Time complexity O(n1+n2+...), space complexity O(1)
class Solution:
def merge(self, intervals: list[list[int]]) -> list[list[int]]:
result = []
for newInterval in intervals:
self.insert(result, newInterval)
return result

def insert(self, intervals: list[list[int]], newInterval: list[int]) -> None:
i = 0
while i < len(intervals):
cur = intervals[i]
if newInterval[1] < cur[0]:
intervals.insert(i, newInterval)
return
elif newInterval[0] > cur[1]:
i += 1
else:
newInterval[0] = min(newInterval[0], cur[0])
newInterval[1] = max(newInterval[1], cur[1])
intervals.pop(i)
intervals.append(newInterval)

相关题目