# 30.插入区间

### 描述

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

### 样例

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

/**
* Definition of Interval:
* class Interval {
* public:
*     int start, end;
*     Interval(int start, int end) {
*         this->start = start;
*         this->end = end;
*     }
* }
*/

class Solution {
public:
/*
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/

vector<Interval> insert(vector<Interval> intervals, Interval newInterval) {
// write your code here
int count = 0;
int i = 0;
while(i < intervals.size()){
if(newInterval.end < intervals[i].start) break;
else if(newInterval.start > intervals[i].end)
++i;
else{
newInterval.start = min(intervals[i].start,newInterval.start);
newInterval.end = max(intervals[i].end,newInterval.end);
++i;
++count;
}
}
if(count > 0) intervals.erase(intervals.begin()+i-count,intervals.begin()+i);
intervals.insert(intervals.begin()+i-count,newInterval);
return intervals;
}

};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120