给出一个区间的集合, 请合并所有重叠的区间。
示例:
给出 [1,3],[2,6],[8,10],[15,18]
,
返回 [1,6],[8,10],[15,18]
.
贪心,先以start大小排序,这样保证start的是有序的。
然后扩张end。代码也很容易理解,复杂度是nlogn
/**
* 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;
if (intervals.empty())
return res;
sort(intervals.begin(), intervals.end(), [](Interval const& i1, Interval const& i2) {return i1.start < i2.start;});
res.push_back(intervals[0]);
int cur = 0;
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i].start > res[cur].end) {
res.push_back(intervals[i]);
cur++;
}
else {
res[cur].end = max(res[cur].end, intervals[i].end);
}
}
return res;
}
};