57. 插入区间
题目链接:57. 插入区间
代码如下:
cpp
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
//插入后进行区间合并
intervals.push_back(newInterval);
sort(intervals.begin(),intervals.end());
for (int i = 0; i < intervals.size(); i++)
{
int left = intervals[i][0], right = intervals[i][1];
//结果为空或者上个区间的右端点小于现区间的左端点,证明不连续,就放进去
if (res.empty() || res.back()[1] < left)
{
res.push_back({left,right});
}
else//连续,就更新左右端点
{
res.back()[1] = max(res.back()[1], right);
}
}
return res;
}
};