题目:
给出一个区间的集合,请合并所有重叠的区间。
示例 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] 可被视为重叠区间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-intervals
解法:
1.将每个区间的首尾拆分为两个列表head和tail,分别进行排序;
2.遍历尾列表,当尾列表的当前值,小于首列表当前对应值的下一位时(tail[i]<head[i+1]),合并区间产生。
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
n = len(intervals)
if n<=1:
return intervals
head = []
tail = []
result = []
for [i,j] in intervals:
head.append(i)
tail.append(j)
head.sort()
tail.sort()
i = 0
for j in range(n-1):
if tail[j]<head[j+1]:
result.append([head[i], tail[j]])
i = j+1
result.append([head[i], tail[j+1]])
return result