Insert Interval

update Aug 12,2017 12:37

LeetCodearrow-up-right

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].

Basic Idea:

这里arrow-up-right 有一个很好的分析文章,关于这一系列题目。

首先的一个思路是直接将newInterval插入,然后执行之前 merge intervals 那道题目的算法。但是由于此题所给条件是intervals已经排序且没有overlapping,用merge的算法会浪费很多时间。由此我们可以想到一种优化的方法:

在遍历的时候,intervals会被分为三段:

  • 在 newInterval 左边,无交集;

  • 有交集;

  • 在 newInterval 右边,无交集;

于是我们可以根据这个性质,用三个while循环分别处理。

Java Code:

Python Code: