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