leetcode--57--Insert Interval

问题描述:

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的区别。

    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000013724899
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞