题目链接:https://leetcode-cn.com/problems/insert-interval/solution/
题目描述:
题解:
class Solution {
public:
static bool cmp(vector<int> a, vector<int> b)
{
return a[0] < b[0];
}
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> ans;
int left = newInterval[0];
int right = newInterval[1];
for(auto &item : intervals)
{
if(item[1] < left) //与当前节点无交集,插入值左边界大于当前节点的右边界
{
ans.push_back(item);
}else if(item[0] > right) //与当前节点无交集,插入值右边界小于当前节点的左边界
{
ans.push_back(item);
}else //有交集
{
left = min(item[0], left);
right = max(item[1], right);
}
}
ans.push_back({left, right});
sort(ans.begin(), ans.end(), cmp); //按左边界排序
return ans;
}
};