Description
Given a collection of intervals, merge all overlapping intervals.
Example
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
思路
- 先按照start从小到大排序,然后遍历一遍,找出新的区间
代码
/**
* 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:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
int len = intervals.size();
if(len == 0) return res;
sort(intervals.begin(), intervals.end(),
[](const Interval &a, const Interval &b){
if(a.start != b.start)
return a.start < b.start;
else return a.end < b.end;
});
int i = 0;
while(i < len){
Interval tmp;
tmp.start = intervals[i].start;
tmp.end = intervals[i].end;
while(i + 1 < len && intervals[i + 1].start <= tmp.end){
tmp.end = max(tmp.end, intervals[i + 1].end);
i++;
}
res.push_back(tmp);
i++;
}
return res;
}
};