原题如下:
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]
.
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
bool cmp(Interval a,Interval b){
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval>v;
sort(intervals.begin(),intervals.end(),cmp);
int left = -1,right = -1;
for(int i = 0; i < intervals.size(); i++){
if(intervals[i].start <= right)
right = max(right,intervals[i].end);
else{
if(left != -1){
v.push_back(Interval(left,right));
}
left = intervals[i].start;
right = intervals[i].end;
}
}
if(left != -1){
v.push_back(Interval(left,right));
}
return v;
}
};