思路:按左边界排序,若相邻两个区间重叠(表现为
intervals[i][0] <= end
),则更新最大右边界end,这样就可以合并更多的区间了,整体最优:合并所有重叠的区间。
class Solution {
public:
static bool cmp(const vector<int> &a, const vector<int> &b){
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if(intervals.size() == 1) return intervals;
sort(intervals.begin(), intervals.end(), cmp);
vector<vector<int> > res;
int end = intervals[0][1], begin = intervals[0][0];
for(int i = 1; i < intervals.size(); i++){
if(intervals[i][0] <= end){
end = max(end, intervals[i][1]);
}
else{
res.push_back({begin, end});
begin = intervals[i][0];
end = intervals[i][1];
}
if(i == intervals.size() - 1)
res.push_back({begin, end});
}
return res;
}
};