码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 56. Merge Intervals

时间:2019-09-02 18:56:08      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:question   append   end   not   splay   code   problems   一个   one   

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

 

Leetcode 56. Merge Intervals

标签:question   append   end   not   splay   code   problems   一个   one   

原文地址:https://www.cnblogs.com/pegasus923/p/11448055.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!