原题链接:Leetcode 56. Merge Intervals
Given an array of intervals
where intervals[i] = [starti, endi]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
- 1 <= intervals.length <= 104
- intervals[i].length == 2
- 0 <= starti <= endi <= 104
方法一:排序
思路:
首先对所有区间按左节点升序排序
然后遍历每个区间:
- 当前节点的左节点处于上个区间中时,用当前节点的右节点更新上个区间的右节点
- 否则说明当前区间和上个区间是不相交的,当前区间直接加入结果集
C++代码:
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
// 提前返回
if (intervals.size() == 0) {
return {};
}
// 按左端点升序排列
sort(intervals.begin(), intervals.end());
vector<vector<int>> ans;
// 遍历每个区间
for (int i = 0; i < intervals.size(); ++i) {
// lr左右端点
int l = intervals[i][0], r = intervals[i][1];
// 分隔的区间 加入结果
if (!ans.size() || ans.back()[1] < l) {
ans.push_back({l, r});
}
// 区间合并
else {
ans.back()[1] = max(ans.back()[1], r);
}
}
return ans;
}
};
复杂度分析:
- 时间复杂度:O(nlogn),排序占了大头
- 空间复杂度:O(logn),排序用掉的空间