Python Solution


  • 0
    A
    # 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]
            """
            if len(intervals) == 0:
                return []
            ret = []
            # Sort by interval start
            intervals.sort(key= lambda x: x.start)
            base = intervals.pop(0)
            while len(intervals) > 0:
                cur = intervals.pop(0)
                # If the former is a bigger interval than the current one,
                # merge them.
                if base.end >= cur.start:
                    base.start = min(base.start,cur.start)
                    base.end = max(base.end,cur.end)
                # These are non-overlapping, so append to our list and
                # make the current one as our base 
                else:
                    ret.append(base)
                    base = cur
            
            ret.append(base)
            
            return ret
            ```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.