先把区间进行排序,start小的放在前面
只要该区间和前面区间有交叉,就合并这两个区间,即该区间的start小于等于前区间的end.
合并的区间为[intervals[index-1].start,max(intervals[index].end,intervals[index-1].end)]
/**
* 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 cmp(Interval a,Interval b){
return a.start<b.start;
}
vector<Interval> merge(vector<Interval> &intervals) {
sort(intervals.begin(),intervals.end(),cmp);
int i=0;
for(i=0;i<intervals.size();i++){
if(i>0&&intervals[i].start<=intervals[i-1].end){
//如果该区间的start小于等于前区间的end,说明两个区间可以合并
int start=intervals[i-1].start;
int end=max(intervals[i].end,intervals[i-1].end);
intervals.erase(intervals.begin()+i-1);
intervals.erase(intervals.begin()+i-1);
intervals.insert(intervals.begin()+i-1,Interval(start,end));
i--;
}
}
return intervals;
}
};