插入区间 insert-interval
题目描述
给定一组不重叠的时间区间,在时间区间中插入一个新的时间区间(如果有重叠的话就合并区间)。
这些时间区间初始是根据它们的开始时间排序的。
示例1:
给定时间区间[1,3],[6,9],在这两个时间区间中插入时间区间[2,5],并将它与原有的时间区间合并,变成[1,5],[6,9].
示例2:
给定时间区间[1,2],[3,5],[6,7],[8,10],[12,16],在这些时间区间中插入时间区间[4,9],并将它与原有的时间区间合并,变成[1,2],[3,10],[12,16].
这是因为时间区间[4,9]覆盖了时间区间[3,5],[6,7],[8,10].
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].
解题思路
-
借鉴合并区间的思路,由于intervals初始有序,因此遍历intervals数组,寻找newInterval正确的插入位置。插入后,就变成了合并区间问题,直接套用模板即可。
-
vector中insert()的用法:
insert(it, x)用来向vector 的任意迭代器it 处插入一个元素x ,时间复杂度O(N)。
vector<int> vi; for (int i = 1; i <= 5; i++) { vi.push_back(i); //此时为1 2 3 4 5 } vi.insert(vi.begin() + i, -1); //将-1插入vi中数组下标为2的位置 /* 输出结果为1 2 -1 3 4 5 */
因此,将元素x插入到数组中下标为i的位置写法为:
it.insert(it.begin() + i, -1)
-
此题代码如下:
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> res;
if(!intervals.size()) {
res.push_back(newInterval);
return res;
}
//由于intervals初始有序,因此遍历数组,寻找newInterval正确的插入位置
for(int i = 0; i < intervals.size(); i ++) {
if(newInterval.start <= intervals[i].start) {
intervals.insert(intervals.begin() + i, newInterval);
break;
}
}
//如果newInterval比所有区间都大,则直接添加在最后
if(newInterval.start > intervals.back().start) {
intervals.push_back(newInterval);
}
//以下为区间合并的模板
res.push_back(intervals[0]);
for(int i = 1; i < intervals.size(); i ++) {
Interval temp = intervals[i];
//如果存在重叠
if(res.back().end >= temp.start) {
res.back().end = max(res.back().end, temp.end);
} else {
res.push_back(temp);
}
}
return res;
}
};