力扣---插入区间

给你一个无重叠的 *,*按照区间起始端点排序的区间列表。

在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。

思路:分类讨论 合并区间

代码:

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;
    }
};
相关推荐
1-1=019 分钟前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和202727 分钟前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi42 分钟前
力扣73 矩阵置零
算法·leetcode·矩阵
布莱克60511 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH14 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
石小石Orz15 小时前
AI 正在蚕食我们的编码能力
前端·后端·算法
民乐团扒谱机16 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
青少儿编程课堂16 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
文丑颜不良啊17 小时前
LeetCode2261~2280题目解析
java·leetcode