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]
.
区间合并,分为三种情况
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution{
public:
static bool compare(Interval& a,Interval& b){
return a.start < b.start;
}
vector<Interval> merge(vector<Interval>& intervals){
vector<Interval> res;
int size = intervals.size();
if(size < ) return intervals;
sort(intervals.begin(),intervals.end(),compare);
Interval tmpInterval = intervals[];
for(int i=;i<size;i++){
if(tmpInterval.end < intervals[i].start){
res.push_back(tmpInterval);
tmpInterval = intervals[i];
}else if(tmpInterval.start > intervals[i].end){
res.push_back(intervals[i]);
}else{
tmpInterval.start = min(tmpInterval.start,intervals[i].start);
tmpInterval.end = max(tmpInterval.end,intervals[i].end);
}
}
res.push_back(tmpInterval);
return res;
}
};