题目描述
Given a collection of intervals, merge all overlapping intervals.
样例
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
算法1
Sort then merge, $O(nlogn)$
按照start排序,然后 检查 当前的 interval 是否与 res 的last interval有overlap,如有overlap,则merge and extend last interval,否则将当前interval加到res中。
C++ 代码
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int n = intervals.size();
if(n==0) return intervals;
sort(begin(intervals), end(intervals),
[](const vector<int>& a, const vector<int>& b){ return a[0] < b[0]; });
vector<vector<int>> res;
res.push_back(intervals[0]);
for(int i=1; i<n; i++) {
if(intervals[i][0] <= res.back()[1]) {
// overlap, extend the last interval in res
res.back()[1] = max( res.back()[1], intervals[i][1] );
} else {
// not overlap, append new interval
res.push_back(intervals[i]);
}
}
return res;
}