Python Solution (based on merge intervals)


  • 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 insert(self, intervals, newInterval):
            """
            :type intervals: List[Interval]
            :type newInterval: Interval
            :rtype: List[Interval]
            """
            intervals.append(newInterval)
            intervals.sort(key = lambda intervals: intervals.start)
            if len(intervals) <= 1:
                return intervals
            ind = 1
            stack = []
            stack.append(intervals[0])
            while ind < len(intervals):
                I1 = stack[-1]
                I2 = intervals[ind]
                if I1.end >= I2.start:
                    newI = Interval (min(I1.start,I2.start), max(I1.end,I2.end))
                    stack.pop()
                    stack.append(newI)
                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.