题目
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].
分析
与上一题本质相同,只需要将给定元素插入原 vector,然后将LeetCode 56题代码执行一遍即可!
AC代码
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
//自定义Interval类型元素的升序比较函数
bool cmp(Interval a, Interval b)
{
return a.start < b.start;
}
class Solution {
public:
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
//如果输入参数为空,则返回空vector
if (intervals.empty())
return vector<Interval>(1 , newInterval);
//将新元素插入序列中
intervals.push_back(newInterval);
int len = intervals.size();
//首先,按照每个Integerval的区间首值进行排序,自定义比较
sort(intervals.begin(), intervals.end(), cmp);
//声明结果
vector<Interval> ret;
//定义临时变量
Interval temp = intervals[0];
for (int i = 0; i < len; i++)
{
//换一种判断方法
if (intervals[i].start > temp.end)
{
ret.push_back(temp);
temp = intervals[i];
}
else{
temp.end = temp.end > intervals[i].end ? temp.end : intervals[i].end;
}//else
}//for
ret.push_back(temp);
return ret;
}
};