合并区间融合

在这里插入图片描述

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
  public:

    vector<Interval> merge(vector<Interval>& vec) {
        if (vec.empty() || vec.size() == 1)
            return vec;

        sort(vec.begin(), vec.end(),  [](Interval a, Interval b) -> bool { return a.start < b.start; });
        Interval tep;
        tep.start = 0;
        tep.end = 0;
        stack<int>sta;
        sta.push(vec[0].start);
        sta.push(vec[0].end);
        for (int i = 1; i < vec.size(); i++) {
            if (sta.top() >= vec[i].start) {
                int t1 = sta.top();
                sta.pop();
                int t0 = sta.top();
                sta.pop();
                if (t0 <= vec[i].start) {
                    t1 = max(t1, vec[i].end);
                    sta.push(t0);
                    sta.push(t1);
                }
            }else{
                sta.push(vec[i].start);
                sta.push(vec[i].end);
            }
        }
        tep.start = 0;
        tep.end = 0;
        vector<Interval>res = vector<Interval>(sta.size()/2, tep);
        int index = res.size() - 1;
        while (!sta.empty()) {
            if (sta.size() % 2 == 0) {
                tep.end = sta.top();
                sta.pop();
            } else {
                tep.start = sta.top();
                sta.pop();
            }
            if (sta.size() % 2 == 0){
                res[index] = tep;
                index--;
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yyd__

你的打赏和鼓励我会珍惜!

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

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

打赏作者

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

抵扣说明:

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

余额充值