排序区间,假设本区间为 now,下区间为 next,如果 next[0] >= now[1],则两区间可以合并。
然后就是一个细节问题,注意到就能 1A
class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int> &b) { return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; }); vector<vector<int>> ans; int begin = -1, finish = -1; for(auto &item : intervals) { if(item[0] <= finish) finish = max(finish, item[1]); else { if(begin != -1) ans.push_back({begin, finish}); begin = item[0]; finish = item[1]; } } ans.push_back({begin, finish}); return ans; } };