这一题不能用差分数组,因为 [1 , 4] [5, 6] 这个就会被合并,正确的做法就是先排序
bool cmp(vector<int> a, vector<int> b) {
if (a[0] < b[0]) return 1;
if (a[0] == b[0]) return a[1] < b[1];
return 0;
}
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
int l = intervals[0][0], r = intervals[0][1];
vector<vector<int>> ans;
for (int i = 1; i < intervals.size(); i++) {
int ll = intervals[i][0], rr = intervals[i][1];
if (ll > r) {
ans.push_back({ l,r });
l = ll, r = rr;
}
else if (ll <= r) {
if (rr <= r) {
continue;
}
else if (rr > r) {
r = rr;
}
}
}
ans.push_back({ l,r });
return ans;
}
};