思路:也没啥好说的了,就是模拟然后注意输入可能为空的判断。运用运算符重载先sort一波。应该有更简单的解法,待我研究出来再更新。
class Solution { public: static bool cmp(pair<int, int> P1, pair<int, int> P2) { if(P1.first != P2.first) { return P1.first < P2.first; } return P1.second < P2.second; } vector<vector<int>> merge(vector<vector<int>>& intervals) { if(intervals.size() == 0) { return intervals; } vector<pair<int, int>> v; for(int i = 0; i < intervals.size(); ++i) { v.push_back(pair<int, int>(intervals[i][0], intervals[i][1])); } sort(v.begin(), v.end(), cmp); pair<int, int> temp = v[0]; vector<pair<int, int>> ans; for(int i = 1; i < v.size(); ++i) { if(temp.second >= v[i].first) { if(temp.second <= v[i].second) temp = pair<int, int>(temp.first, v[i].second); } else { ans.push_back(temp); temp = v[i]; } } ans.push_back(temp); vector<vector<int>> f; for(int i = 0; i < ans.size(); ++i) { vector<int>sb; sb.push_back(ans[i].first); sb.push_back(ans[i].second); f.push_back(sb); } return f; } private: };