解题思路
先将该新区间插入数组中,之后按区间的起始点进行排序,
之后遍历该数组,对区间进行合并,最后返回结果。
代码
#include<algorithm>
bool cmp(const Interval& a,const Interval& b){return a.start < b.start;
}
class Solution {
public:vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {if(intervals.size() == 0){intervals.push_back(newInterval);return intervals;}intervals.push_back(newInterval);sort(intervals.begin(),intervals.end(),cmp);vector<Interval>res;int start = intervals[0].start;int end = intervals[0].end;for(int i = 1;i < intervals.size();i++){if(intervals[i].start <= end && intervals[i].end > end){end = intervals[i].end;}else if(intervals[i].start > end){res.push_back(Interval(start,end));start = intervals[i].start;end = intervals[i].end;}elsecontinue;}res.push_back(Interval(start,end));return res;}
};