The same as merge intervals, python


  • 0
    B
    class Solution:
    # @param intervals, a list of Intervals
    # @param newInterval, a Interval
    # @return a list of Interval
    def insert(self, intervals, newInterval):
        if newInterval==None:
            return intervals
        if len(intervals)==0:
            return [newInterval]
        
        result=[]
        
        i=0
        while i<len(intervals):
            if intervals[i].start>=newInterval.start:
                break
            i=i+1
        intervals.insert(i,newInterval)
        
        start=intervals[0].start
        end=intervals[0].end
        
        for index in range(1,len(intervals)):
            if intervals[index].start>end:
                result.append(Interval(start,end))
                start=intervals[index].start
                end=intervals[index].end
            elif intervals[index].start<=end:
                if intervals[index].end>end:
                    end=intervals[index].end
                        
        result.append(Interval(start,end))
        
        return result

Log in to reply
 

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