Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
Return [1,6],[8,10],[15,18]
.
Idea: began to want to use line segment tree, later think of this is not a dynamic change is not necessary.
Sort by the first value of the interval from small to large, and then skip over the range that is covered later.
Sort toss for a long time, began to do not have to write a merge sort. Now the sort in the code is available.
classSolution { Public: Vector<Interval> Merge (Vector<interval> &intervals) { //mysort (intervals, 0, intervals.size ()-1);sort (Intervals.begin (), Intervals.end (), comp); Vector<Interval>ans; Interval tmp; for(inti =0; I < intervals.size (); i++)//find each successive interval {Tmp.start=Intervals[i].start; intCurmaxend =intervals[i].end;//Note that the maximum value of the current interval is recorded because it is possible [1,100],[2,3] so that the front maximum is larger than the back while(i +1< Intervals.size () && curmaxend >= intervals[i +1].start) {curmaxend= (Intervals[i +1].end > Curmaxend)? Intervals[i +1].end:curmaxend; I++; } tmp.end=Curmaxend; Ans.push_back (TMP); } returnans; } voidMysort (vector<interval> &intervals,intSinte) {if(S >= e)return; intm = (s + e)/2; Mysort (intervals, S, m); Mysort (intervals, M+1, E); Merge (intervals, S, M, e); } voidMerge (Vector<interval> &intervals,intSintMinte) {vector<Interval> Left (Intervals.begin () + S, intervals.begin () + M +1); Vector<Interval> Right (Intervals.begin () + M +1, Intervals.begin () + E +1); intL =0, r =0, n =s; while(L < Left.size () && R <right.size ()) {Intervals[n+ +] = (Left[l].start < Right[r].start)? left[l++]: right[r++]; } while(L <left.size ()) {Intervals[n+ +] = left[l++]; } while(R <right.size ()) {Intervals[n+ +] = right[r++]; } } Static BOOLCompConstinterval& A,Constinterval&b) { returnA.start <B.start;}};
"Leetcode" Merge intervals (hard)