Problem:
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.
思路:
将区间的左端点按从小到大进行排序,然后观察相邻2个区间是否有公共部分,如果有公共部分则选取右端点的最大值作为新的区间的右端点,如果无公共部分则直接添加新区间。
Solution:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.empty()) return vector<vector<int>>{};
vector<vector<int>> res;
sort(intervals.begin(), intervals.end(), [] (vector<int> a, vector<int> b) {return a.front() < b.front();});
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (res.back().back() < intervals[i].front()) res.push_back(intervals[i]);
else
res.back().back() = max (res.back().back(), intervals[i].back());
}
return res;
}
性能:
Runtime: 80 ms Memory Usage: 26.5 MB