将所有区间按左端点从小到大排序
1. 无交集 : 则保存当前区间
2. 有交集 : 则更新右端点
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> res;
sort(intervals.begin(), intervals.end());
int l = -2e9, r = -2e9;
for (auto s : intervals)
if (r < s[0]) {
if (l != -2e9) res.push_back({l, r});
l = s[0], r = s[1];
}
else r = max(r, s[1]);
if (l != -2e9) res.push_back({l, r});
return res;
}
};
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& a) {
vector<vector<int>> res;
if (a.empty()) return res;
sort(a.begin(), a.end());
int l = a[0][0], r = a[0][1];
for (int i = 1; i < a.size(); i ++) {
if (r < a[i][0]) {
res.push_back({l, r});
l = a[i][0], r = a[i][1];
}
else r = max(r, a[i][1]);
}
res.push_back({l, r});
return res;
}
};