leetcode–57–Insert Interval

龍仔發表於2019-02-16

問題描述:

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

Example 2:

Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as
[1,2],[3,10],[12,16].

This is because the new interval [4,9] overlaps with
[3,5],[6,7],[8,10].

class Solution(object):
    def insert(self, intervals, newInterval):
        """
        :type intervals: List[Interval]
        :type newInterval: Interval
        :rtype: List[Interval]
        """
        start=newInterval.start
        end=newInterval.end
        # print(`start,end`,start,end)
        outs=list()
        index=0
        flag_break=0
        for index,interval in enumerate(intervals):
            if interval.end>=start:
                if interval.start>end:
                    flag_break=1
                    break
                else:
                    start=min(start,interval.start)
                    end=max(end,interval.end)
                    # print(`start,end:`, start, end)

            else:
                outs.append(interval)
        outs.append(Interval(start,end))
        if flag_break:
            outs.extend(intervals[index:])
        # print(outs)
        outs_num=[ (out.start,out.end) for out in outs]
        return outs_num

分析:這道題的關鍵在於理解問題,抽取原型,理解中間可以merge部分如何界定,以及非merge部分如何進行追加list。 需要注意的是:迴圈到最後一個元素和在最後一個元素break的區別。

相關文章