遍历整个数组,依次合并操作!
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> result;
int a=newInterval[0],b=newInterval[1];
int fg=0; //纪录newInterval 是否合并完成或者加入result(就是不存在重叠部分了)
int c,d;
for(int i=0;i<intervals.size();i++){ // 遍历整个数组进行合并操作
c=intervals[i][0];
d=intervals[i][1];
if(d<a){ // 区间[c,d]整个在[a,b]前面,那就不需要合并,直接加入result
result.push_back(intervals[i]);
}
// [a,b] 完全在 [c,d] 前,说明[a,b]可以加入result中了
// fg==0说明纪录newInterval还没有合并到result中
else if(fg==0 && b<c){
vector<int> temp;
temp.push_back(a);
temp.push_back(b);
result.push_back(temp);
fg=1; // 标注已经加入,后面无需再合并了
result.push_back(intervals[i]);
}
//[a,b] 完全在 [c,d] 前
// fg==1 无需合并,直接加入
else if(fg==1 && b<c){
result.push_back(intervals[i]);
}
// 重叠 ,合并
else if((a>=c && a<=d) ||(b>=c && b<=d)){
a=min(a,c);
b=max(b,d);
}
}
// 退出循环了fg还为0说明,合并的结果没有加入到result
if(fg==0){
vector<int> temp;
temp.push_back(a);
temp.push_back(b);
result.push_back(temp);
}
return result;
}
};