"Leetcode" Merge intervals (hard)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.