leetcode合并时间区间

给定一组非重叠的时间间隔的,插入一个新的时间间隔成区间(可能需要合并)。
实施例1:给定的时间间隔[1,3],[6,9],插入并在如[1,5]合并[2,5],[6,9]。
实施例2:给定[1,2],[3,5],[6,7],[8,10],[12,16],插入和作为合并[4,9]后为[1,2],[3,10],[12,16]。

时间复杂度O(n),空间复杂度O(1)
CODE

#define  _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<vector>
struct Interval
{
    int _start;
    int _end;
    Interval(int s,int e)
        :_start(s),
        _end(e)
      {}
};

class Solution
{
public:
    void Insert(Interval tmp)
    {
        vector<Interval>::iterator it = _root.begin();
        while (it != _root.end())
        {
            if (tmp._end < it->_start)
            {
                _root.insert(it, tmp);
                return;
            }
            else if (tmp._start>it->_end)
            {
                it++;
                continue;
            }
            else
            {
                if (tmp._start > it->_start)
                {
                    tmp._start = it->_start;
                }
                if (tmp._end < it->_end)
                {
                    tmp._end = it->_end;
                }
                it = _root.erase(it);
            }
        }
        _root.insert(_root.end(), tmp);
    }

    void Disp()
    {
        for (size_t i = 0; i < _root.size(); i++)
        {
            cout << "[" << _root[i]._start << "," << _root[i]._end << "]" << endl;
        }
    }
private:
    vector<Interval> _root;

};

void test()
{
    Interval i1(2, 6);
    Interval i2(3, 8);
    Interval i3(-3, 1);
    Interval i4(10, 13);
    Interval i5(-2, 1);
    Solution s;
    s.Insert(i1);
    s.Insert(i2);
    s.Insert(i3);
    s.Insert(i4);
    s.Insert(i5);
    s.Disp();
}

int main()
{
    test();
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值