题干:
代码:
class Solution {
public:static bool cmp(vector<int>& a, vector<int>& b){return a[0] < b[0];}vector<vector<int>> merge(vector<vector<int>>& intervals) {sort(intervals.begin(), intervals.end(), cmp);vector<vector<int>> res;res.push_back(intervals[0]);for(int i = 1; i < intervals.size(); i++){if(intervals[i][0] <= res.back()[1]){if(intervals[i][1] > res.back()[1]){res.back()[1] = intervals[i][1];}}else res.push_back(intervals[i]);}return res;}
};
注意到全程参与比较的只有第i位数据和res.back()。重叠,判断右边界是否被囊括(大于则更新),如果不重叠则直接加入res。