zoukankan      html  css  js  c++  java
  • 352[LeetCode] Data Stream as Disjoint Intervals

    Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals.

    For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:

    [1, 1]
    [1, 1], [3, 3]
    [1, 1], [3, 3], [7, 7]
    [1, 3], [7, 7]
    [1, 3], [6, 7]



    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<cstdio>
    
    using namespace std;
     
                            
    
    
    struct Interval {
        int start;
        int end;
        Interval() : start(0), end(0) {}
        Interval(int s, int e) : start(s), end(e) {}
    };
    bool Cmp(Interval a, Interval b) { return a.start < b.start; }//不能将其放在class SummaryRange中
    class SummaryRanges { public: void addNum(int val) { vector<Interval>::iterator it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp); int start = val, end = val; if(it != vec.begin() && (it-1)->end+1 >= val) it--; while(it != vec.end() && val+1 >= it->start && val-1 <= it->end) { start = min(start, it->start); end = max(end, it->end); it = vec.erase(it); } vec.insert(it,Interval(start, end)); } vector<Interval> getIntervals() { return vec; } private: vector<Interval> vec; }; /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges* obj = new SummaryRanges(); * obj->addNum(val); * vector<Interval> param_2 = obj->getIntervals(); */ int main(){ SummaryRanges* obj =new SummaryRanges(); obj->addNum(1); obj->addNum(2); obj->addNum(5); obj->addNum(6); obj->addNum(3); vector<Interval> param_2 = obj->getIntervals(); cout<<param_2[0].start<<"------"<<param_2[0].end<<endl; cout<<param_2[1].start<<"------"<<param_2[1].end<<endl; }


    易错点:

    vector<Interval>::iterator it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp);
    lower_bound()返回的是从begin到end之间的按照Cmp排序的首个大于等于Interval(val,val)的地址;

    因此it 声明应该是 vector<Interval>::iterator it
    之前错误的声明为 Interval* it 则出现报错:[Error] cannot convert '__gnu_cxx::__normal_iterator<Interval*, std::vector<Interval> >' to 'Interval*' in initialization


    
    
  • 相关阅读:
    Browse information of one or more files is not available解决办法
    python中装饰器的使用
    python:匿名函数lambda
    python:列表生成式的学习
    python:列表切片知识的总结
    python:*args和**kwargs的用法
    NAT
    ACL
    三层交换技术和HSRP协议
    单臂路由与DHCP中继
  • 原文地址:https://www.cnblogs.com/250101249-sxy/p/10424840.html
Copyright © 2011-2022 走看看