###### #30 Insert Interval

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].

1. 把new interval加入到intervals的array中，然后把整个array的所有区间根据start来sort

2. 遍历这个sort过的区间集合。如果发现本区间和上一个区间有overlap（本区间的start在上一个区间中），那么就合并本区间和上一个区间；然后不断的check下一个区间，如果有overlap就再进行合并，直到没有overlap为止。

3. 把最终的区间写到ans中。

Mycode（AC = 26ms）：

/**
* Definition of Interval:
* class Interval {
* public:
*     int start, end;
*     Interval(int start, int end) {
*         this->start = start;
*         this->end = end;
*     }
* }
*/
class Solution {
public:
/**
* Insert newInterval into intervals.
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> ans;

// sort the whole intervals according to start
auto comp = [](const Interval& a, const Interval& b) {
return a.start <= b.start;
};

intervals.push_back(newInterval);
sort(intervals.begin(), intervals.end(), comp);

int len = intervals.size();
for (int i = 1; i < len; i++) {
// if interval i has overlap with interval i - 1, then
// merge 2 intervals
while (i < len && intervals[i].start <= intervals[i - 1].end) {
intervals[i].start = intervals[i - 1].start;
intervals[i].end = max(intervals[i].end, intervals[i - 1].end);
i++;
}
ans.push_back(intervals[i - 1]);
if (i >= len) return ans;
}

ans.push_back(intervals[len - 1]);
return ans;
}
};

#### Insert Interval

2015-09-30 17:20:03

#### (Java)LeetCode-57. Insert Interval

2016-10-05 15:49:00

#### LeetCode Insert Interval

2014-03-20 13:40:08

#### Lintcode30 Insert Interval solution 题解

2017-04-23 21:20:42

#### Lintcode_30 Insert Interval

2016-06-28 14:23:59

#### lintcode 30 Insert Interval

2018-03-28 11:20:42

#### 【简单】Lintcode 30:Insert Interval

2018-01-23 21:45:51

#### Lintcode_30 Insert Interval

2016-06-28 14:23:59

#### leetcode20: Insert Interval

2013-01-08 15:25:19

#### 【LintCode】Insert Intervals 插入区间

2015-07-16 10:56:53

## 不良信息举报

#30 Insert Interval