给你一个无重叠的 *,*按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
思路:分类讨论 合并区间
代码:
cpp
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
int length = intervals.size();
int i = 0;
int flag = 0;
if(length == 0){
res.push_back(newInterval);
return res;
}
for (; i < length; i++) {
if (intervals[i][1] < newInterval[0])
res.push_back(intervals[i]);
else if ((newInterval[0] <= intervals[i][0]) && (newInterval[1] >= intervals[i][1])) {}
else if ((newInterval[0] > intervals[i][0]) && (newInterval[1] >= intervals[i][1])) {
newInterval[0] = intervals[i][0];
continue;
}
else if ((newInterval[0] > intervals[i][0]) && (newInterval[1] < intervals[i][1])) {
newInterval[0] = intervals[i][0];
newInterval[1] = intervals[i][1];
continue;
}
else if ((newInterval[0] <= intervals[i][0]) && (newInterval[1] > intervals[i][0]) && (newInterval[1] < intervals[i][1])) {
newInterval[1] = intervals[i][1];
continue;
}
else if (newInterval[0] == intervals[i][1]) {
newInterval[0] = intervals[i][0];
continue;
}
else if (newInterval[1] == intervals[i][0]) {
newInterval[1] = intervals[i][1];
continue;
}
else if (newInterval[1] < intervals[i][0]) {
res.push_back(newInterval);
flag = 1;
break;
}
}
if(flag == 0)
res.push_back(newInterval);
for (; i < length; i++) {
res.push_back(intervals[i]);
}
return res;
}
};