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

LeetCode开心刷题四十二天——56. Merge Intervals

时间:2019-09-16 09:20:11      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:inter   xpl   val   interval   into   ide   初始   amp   col   

56. 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.
思路:
对所有按键值排序,看下一个是和它合并还是单独存储
class Solution(object):
    def merge(self, intervals):
        ans = []
        # 使用下标表示interval里的是按哪个排序
        for interval in sorted(intervals, key=lambda x: x[0]):
            # 如果初始或者当前与上一个足够拉开差距,直接压入
            if not ans or interval[0] > ans[-1][1]:
                ans.append(interval)
            # 否则扩展上一个ans的范围
            else:
                ans[-1][1] = max(ans[-1][1], interval[1])
        return ans

solu=Solution()
intervals=[[1,3],[2,6],[8,10],[15,18]]
print(solu.merge(intervals))

 

LeetCode开心刷题四十二天——56. Merge Intervals

标签:inter   xpl   val   interval   into   ide   初始   amp   col   

原文地址:https://www.cnblogs.com/Marigolci/p/11525461.html

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