Topic:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
Assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge in as [2,5]
[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge in as [4,9]
[1,2],[3,10],[12,16]
.
This is because, the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
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) {} *}; */classSolution { Public: Vector<Interval> Insert (vector<interval>&intervals, Interval newinterval) {Vector<Interval>ret; inti =0; //Search for start insert position for(; I<intervals.size (); + +i) {if(Newinterval.start >intervals[i].end) {Ret.push_back (intervals[i]); } Else { Break; } } //NewInterval larger than all the existed intervals if(i==intervals.size ()) {Ret.push_back (newinterval); returnret; } intStart =std::min (Intervals[i].start, Newinterval.start); //Search for the end insert position for(; I<intervals.size (); + +i) {if(Newinterval.end <= Intervals[i].end) Break; } //NewInterval End is larger than all the range if(i==intervals.size ()) {Ret.push_back (Interval (Start, newinterval.end)); returnret; } if(newinterval.end<Intervals[i].start) {Ret.push_back (Interval (start,newinterval.end)); Ret.insert (Ret.end (), Intervals.begin ()+I, Intervals.end ()); returnret; } if(newinterval.end==Intervals[i].start) {Ret.push_back (Interval (start,intervals[i].end)); if(I<intervals.size ()-1) {Ret.insert (Ret.end (), Intervals.begin ()+i+1, Intervals.end ()); } returnret; } if(Newinterval.end >Intervals[i].start) {Ret.push_back (Interval (start,intervals[i].end)); if(I<intervals.size ()-1) {Ret.insert (Ret.end (), Intervals.begin ()+i+1, Intervals.end ()); } returnret; } }};
Tips
The overall feeling of this problem is very cumbersome, because to consider various boundary conditions, and so on or unequal; Although AC but this version of the code is ugly.
See if I can change the version of the beautiful.
"Insert Interval" cpp