Straight forward python


  • 0
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        if not intervals:
            return [newInterval]
        if newInterval.start > intervals[-1].end:
            return intervals + [newInterval]
        if newInterval.end < intervals[0].start:
            return [newInterval] + intervals
        s = e = -1
        if newInterval.start <= intervals[0].start:
            merge_s = 0
            s = newInterval.start
        if newInterval.end >= intervals[-1].end:
            merge_e = len(intervals) - 1
            e = newInterval.end
        if s == -1:
            for i in xrange(len(intervals)):
                if newInterval.start <= intervals[i].end:
                    merge_s = i
                    s = min(newInterval.start, intervals[i].start)
                    break
        if e == -1:
            for i in xrange(len(intervals) - 1, -1, -1):
                if newInterval.end >= intervals[i].start:
                    merge_e = i
                    e = max(newInterval.end, intervals[i].end)
                    break
        interval_new = Interval()
        interval_new.start = s
        interval_new.end = e
        return intervals[:merge_s] + [interval_new] + intervals[merge_e + 1:]

Log in to reply
 

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