排序后迭代,遇到符合条件的就删除前一项,合并到后一项。
cpp
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
int left = 0,right = 0;
sort(intervals.begin(), intervals.end());
vector<int> tmp;
for(auto it = intervals.begin(); it != --(intervals.end()); )
{
if((*it)[1] >= (*(++it))[0])
{
left = (*(--it))[0];
right = (*it)[1];
it = intervals.erase(it);
right = max(right,(*it)[1]);
tmp.push_back(left);
tmp.push_back(right);
*(it) = tmp;
tmp.clear();
}
}
return intervals;
}
};