Leetcode Merge Intervals

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

Problem-solving ideas: Sort by the left endpoint first, then iterate through the array, temp = intervals[i], if temp and intervals[i+1] have intersection, update the endpoint around temp, continue down until there is no intersection, insert temp into the result set until the end of the array.

In fact, it's all floating clouds, here's the point!

The following code is all in one class, and if the comp function is not static, comp cannot be used in sort, because comp is a member function that declares an instance of a class before it can be accessed. or replace the comp completely with the

[] (const Interval &inter1,const Interval &inter2) {return Inter1.start < Inter2.start;}

This is c++11 new feature, called Lamda expression, defines an anonymous function, 666666666

Static BOOLCompConstinterval& A,Constinterval&b) {    returnA.start <B.start;} Vector<Interval> Merge (Vector<interval> &intervals) {Vector<Interval>result; if(Intervals.empty ()) {returnresult;    } sort (Intervals.begin (), Intervals.end (), comp); Result.push_back (intervals[0]);  for(inti =1; I < intervals.size (); i++){        if(Intervals[i].start <=Result.back (). End)            {Interval temp (result.back (). Start, Max (Result.back (). end, Intervals[i].end));            Result.pop_back ();        Result.push_back (temp); }        Else{result.push_back (intervals[i]); }    }    returnresult;}

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