Leetcode 56. Merge Intervals
Posted pegasus923
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 56. Merge Intervals相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/merge-intervals/
Medium
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.
- 先排序,再挨个比较合并。Solution里对算法有反证,对于排序后的interval list,所有可以合并的interval,肯定是连续出现的。从而证明了算法里只需要把当前interval,跟前一个合并了的interval比较就行。
- https://leetcode.com/problems/merge-intervals/solution/
1 class Solution: 2 def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 if not intervals: 4 return None 5 6 intervals.sort(key=lambda x : x[0]) 7 8 merged = [] 9 10 for interval in intervals: 11 # if the merged interval list is empty or 12 # the current interval does not overlap with the previous, 13 # simply append it. 14 if not merged or merged[-1][1] < interval[0]: 15 merged.append(interval) 16 else: 17 # otherwise, there is overlap, so merge the current and previous intervals. 18 merged[-1][1] = max(merged[-1][1], interval[1]) 19 20 return merged
以上是关于Leetcode 56. Merge Intervals的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 56. 56. Merge Intervals 20170508
java 56.Merge Intervals #LeetCode #Interval