# #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;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：#30 Insert Interval 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)