LeetCode每日一题 (54) 57. 插入区间

57. 插入区间


在这里插入图片描述


遍历整个数组,依次合并操作!

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;
    }
};

在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

战胜.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值