Python solution using a Stack


  • 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) <= 1:
                return intervals
            intervals.sort(key=lambda intervals: intervals.start)
            stack = []
            stack.append(intervals[0])
            length = len(intervals)
            ind = 1
            while ind < length:
                I2 = intervals[ind]
                I1 = stack[-1]
                if I1.end >= I2.start:
                    interval = Interval(min(I1.start,I2.start), max(I2.end,I1.end))
                    stack.pop()
                    stack.append(interval)
                else:
                    stack.append(I2)
                ind+=1
            return stack
            
                    
                
    

Log in to reply
 

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