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]
.
Solution:
The solution is quite straight forward. First we start from the left to find the first interval that is overlapping or right behind the new interval. Once we find this location, we first insert the new interval, and then merge the new interval and the next overlapping intervals into one. It takes O(n) to merge those intervals. Once we meet an interval that is non-overlapping with our new interval, just stop merging.
Code:
/**
* 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) {
if(intervals.empty()){//if intervals are empty, directly insert and return
if(intervals.empty()) intervals.push_back(newInterval);
return intervals;
}
int start_ind = -1;
vector<Interval> res;
//find the location we should insert the new interval
for(int i = 0; i < intervals.size(); i ++){
if(intervals[i].start > newInterval.start){
start_ind = i;
break;
}
if(intervals[i].start <= newInterval.start && intervals[i].end >= newInterval.start){
start_ind = i;
break ;
}
res.push_back(intervals[i]);//collect those non-overlapping set in front of the new interval
}
res.push_back(newInterval);//first insert the new interval
int i = start_ind;
while(i<intervals.size()){
if(res.back().end >= intervals[i].start){//if overlapping, merge the new interval and the next interval into one
res.back().start = min(res.back().start, intervals[i].start);
res.back().end = max(intervals[i].end, res.back().end);
}else{//if the new interval is not overlapping with the next interval, we are done. Collect the rest.
while(i<intervals.size()){
res.push_back(intervals[i]);
i++;
}
break;
}
i++;
}
return res;
}
};