56. Merge Interval
56. Merge Interval
0. 参考文献
序号 | 文献 |
---|---|
1 | 花花酱 LeetCode 56. Merge Intervals |
2 | [LeetCode] Merge Intervals 合并区间 |
1. 题目
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.
2. 思路
本题是对区间的合并。首先需要对输入的区间按第一个数字进行排序。然后把数组的第一个区间放入结果集中,后续的区间依次和其比较。如果能合并就合并,不能的话就把当前区间放入结果集。
3. 实现
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
ret = []
if len(intervals) == 0 :return ret
ret = []
intervals.sort(key = lambda x:x[0])
ret.append(intervals[0])
for i in range(1,len(intervals)):
if intervals[i][0] >= ret[-1][0] and intervals[i][0] <= ret[-1][1] :
t = [ret[-1][0],max(intervals[i][1],ret[-1][1])]
ret[-1] = t
else:
ret.append(intervals[i])
return ret
编程光~