"One Day together Leetcode" #56. Merge intervals

Source: Internet
Author: User

One Day Together Leetcode series (i) Title

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].

(ii) Problem solving
/* Problem Solving steps: 1, the vector inside each interval structure according to the value of start in ascending order 2, traverse the entire intervals, if there is a repeating region on the merge, if not have to save to ret inside * */** * 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>Merge vector<Interval>& intervals) { vector<Interval>Retif(Intervals.empty ())returnRet Sort (Intervals.begin (), Intervals.end (), Comparein);/// in ascending order of start valuesInterval tmp = intervals[0];//Initialize         for(inti =1; I < intervals.size (); i++) {if(intervals[i].start<=tmp.end) tmp.end = max (tmp.end,intervals[i].end);//Update End            Else{ret.push_back (TMP);//No repeat area to press into RETTMP = Intervals[i];//Update the value of TMP to continue traversing}} ret.push_back (TMP);returnRet }Static BOOLComparein (Constinterval& I1,Constinterval& I2)//Comparison function{returni1.start<i2.start; }};

"One Day together Leetcode" #56. Merge intervals

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.