Given a setNon-overlappingIntervals, 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[1,5],[6,9]
.
Example 2:
Given[1,2],[3,5],[6,7],[8,10],[12,16]
, Insert and merge[4,9]
In[1,2],[3,10],[12,16]
.
This is because the new interval[4,9]
Overlaps[3,5],[6,7],[8,10]
.
A non-overlapping interval is given and a new interval is inserted. If the interval overlaps with other intervals, it must be merged.
Note that the question has an assumption that the intervals are sorted Based on the start time, so you do not need to sort them.
struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {}};
Solution: Set the given interval to intervals and the inserted interval to newinterval. You only need to merge the intervals and newinterval,
If the newinterval and intervals do not have an intersection interval, you must insert the newinterval to the corresponding position.
There are three cases for this question
(1) If intervals [I]. End <newinterval. Start, it indicates that intervals [I] And newinterval do not overlap, just retain
(2) If intervals [I]. start> newinterval. end, indicating that intervals [I] And newinterval do not intersect. Insert newinterval. Note that intervals [I] after this time can be retained, because the interval itself does not want to be handed in.
(3) If intervals [I]. Start <newinterval. End, it indicates that the intervals are intersection, merge intervals, and newinterval is updated.
class Solution {public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> res; for(int i = 0 ; i < intervals.size(); ++ i){ if(intervals[i].end < newInterval.start) res.push_back(intervals[i]); else if(intervals[i].start > newInterval.end) { res.push_back(newInterval); newInterval = intervals[i]; }else if(intervals[i].start <= newInterval.end ){ newInterval.start = min(newInterval.start, intervals[i].start); newInterval.end = max(newInterval.end, intervals[i].end); } } res.push_back(newInterval); return res; }};