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

56. Merge Intervals

时间:2017-07-07 20:22:05      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:esc   create   compare   ble   rip   ast   ref   val   object   

https://leetcode.com/problems/merge-intervals/#/solutions

 

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

 


 
 
Sol:
 
Sort intervals according to their start time. 
 
 
Create a new list and append intervals into it. Always compare the start time of the yet-to-add interval to the end time of the last element in the result. ....
 
# Definition for an interval.
class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        
        
        # Just go through the intervals sorted by start coordinate and either combine the current interval with the previous one if they overlap, or add it to the output by itself if they don‘t.
        
        res = []
        for interval in sorted(intervals, key = lambda i : i.start):
            if res and interval.start <= res[-1].end:
                res[-1].end = max(res[-1].end, interval.end)
            else:
                res.append(interval)
        return res

 

56. Merge Intervals

标签:esc   create   compare   ble   rip   ast   ref   val   object   

原文地址:http://www.cnblogs.com/prmlab/p/7133485.html

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