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        
View Python Code

 

posted on 2019-09-02 18:07  浩然119  阅读(118)  评论(0编辑  收藏  举报