Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
题目大意:
intervals列表有一些小区间,合并所有重叠的区间。
解题思路:
合并区间要考虑3种情况:
- [1,3] [2,6] ->[1,6] 第一个区间的end大于等于第二个区间的start且小于第二个区间的end
- [2,8] [3,5] ->[2,8] 第一个区间的end大于等于第二个区间的start且大于等于第二个区间的end
- [1,2] [3,4] -> [1,2] [3,4] 第一个区间的end小于第二个区间的start
刚开始的思路是直接在intervals上比较然后将符合要求的结果值存到res中,但是仅能满足个别情况。后来发现intervals中的元素要逐一与res的最后一个元素比较才行,否则只能两两个小区间比较,有三个及以上的情况就不符合要求了,比如[1,3] [2,6] [5,9][10,12]应该合并为[1,9][10,12],而非[1,6][5,9][10,12]。还需注意一点:将最初待处理列表按照开始区间的大小排序才是题目示例给出的情况,否则如[[1,4],[0,4]]又会出错,应该先排序为[[0,4],[1,4]]再操作。
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) <= 1:
return intervals
intervals.sort()
res = []
for i in range(len(intervals)):
if res == []:
res.append(intervals[i])
else:
if res[-1][1] >= intervals[i][0]:
res[-1][1] = max(intervals[i][1], res[-1][1])
else:
res.append(intervals[i])
return res
参考:https://blog.csdn.net/yangjingjing9/article/details/76512761