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]
.
Idea one: Find the left and right of the overlap, then merge the left~right directly, and add the sides directly to the result.
Don't know why the result is
Submission Result:output Limit exceeded
/** 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) {size_t n=intervals.size (); Vector<Interval>Res; Vector<BOOL> Valid (n,true); Interval merge; if(n = =0) {res.push_back (newinterval); returnRes; }#if0 for(inti =0; I < intervals.size (); i++) {cout<<"["<< Intervals[i].start <<","<< Intervals[i].end <<"]\t" ; } cout<<Endl;#endif intleft =0, right =0; for(inti =0; I < n; i++) { if(Newinterval.start <Intervals[i].start) { Left= i-1; Break; } } if(left = =-1|| Intervals[left].end <newinterval.start) { left++; Merge.start=Newinterval.start; } Else{Merge.start=Intervals[left].start; } for(inti = left; I < n; i++) { if(Newinterval.end <Intervals[i].start) { Right= i-1; Break; } } if(Right = =-1|| Intervals[right].end <newinterval.end) {merge.end=Newinterval.end; } Else{merge.end=Intervals[right].end; } for(inti =0; I < left; i++) {res.push_back (intervals[i]); } res.push_back (merge); for(inti = right+1; I < n; i++) {res.push_back (intervals[i]); } returnRes; }};
Method Two: Directly take the merge function on AC, do not know why ...
BOOLCMP (Interval i, Interval j) {returnI.start <J.start;}classSolution { Public://just reuse the solution of "Merge intervals", quite straight forwardvector<interval> Insert (vector<interval> &intervals, Interval newinterval) {Intervals.push_back (newinterval); returnmerge (intervals);} Vector<Interval> Merge (Vector<interval> &intervals) {size_t n=intervals.size (); Vector<BOOL> Valid (n,true); Vector<Interval>Res; Sort (Intervals.begin (), Intervals.end (), CMP);#if0 for(inti =0; I < intervals.size (); i++) {cout<<"["<< Intervals[i].start <<","<< Intervals[i].end <<"]\t" ; } cout<<Endl;#endif for(inti =1; I < n; i++) {Interval& pre = intervals[i-1]; Interval& cur =Intervals[i]; if(Pre.end >=cur.start) {valid[i-1] =false; Cur.start=Pre.start; if(Pre.end >cur.end) Cur.end=Pre.end; } } for(inti =0; I < n; i++) {//cout << valid[i] << Endl; if(Valid[i] = =true) Res.push_back (Intervals[i]); } returnRes; }};
[Leetcode] Insert Interval