# 合并区间 以下错误的选项是? ## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp ``` ## 答案 ```cpp class Solution { public: vector> merge(vector> &intervals) { vector> res; sort(intervals.begin(), intervals.end(), [](const auto &u, const auto &v) { if (u[0] == v[0]) return u[1] > v[1]; else return u[0] < v[0]; }); auto it = intervals.begin(); int first = (*it)[0], second = (*it)[1]; for (it++; it != intervals.end(); it++) { if ((*it)[0] <= second) second = max(second, (*it)[0]); else { res.push_back({first, second}); first = (*it)[0]; second = (*it)[1]; } } res.push_back({first, second}); return res; } }; ``` ## 选项 ### A ```cpp class Solution { public: vector> merge(vector> &intervals) { vector> res; sort(intervals.begin(), intervals.end()); for (auto it = intervals.begin(); it != intervals.end(); it++) { int first = (*it)[0], second = (*it)[1]; if (!res.size() || res.back()[1] < first) res.push_back({first, second}); else res.back()[1] = max(res.back()[1], second); } return res; } }; ``` ### B ```cpp class Solution { public: vector> merge(vector> &intervals) { sort(intervals.begin(), intervals.end()); vector> res; for (int i = 0; i < intervals.size();) { int t = intervals[i][1]; int j = i + 1; while (j < intervals.size() && intervals[j][0] <= t) { t = max(t, intervals[j][1]); j++; } res.push_back({intervals[i][0], t}); i = j; } return res; } }; ``` ### C ```cpp class Solution { public: static bool cmp(const vector &a, const vector &b) { if (a[0] == b[0]) return a[1] > b[1]; return a[0] < b[0]; } vector> merge(vector> &intervals) { if (intervals.empty()) return intervals; vector> res; int count = 0; sort(intervals.begin(), intervals.end(), cmp); vector temp; temp.push_back(intervals[0][0]); temp.push_back(intervals[0][1]); res.push_back(temp); for (int i = 1; i < intervals.size(); i++) { if (res[count][1] >= intervals[i][0]) { if (res[count][1] <= intervals[i][1]) { res[count][1] = intervals[i][1]; } } else { count++; temp[0] = intervals[i][0]; temp[1] = intervals[i][1]; res.push_back(temp); } } return res; } }; ```