352[LeetCode] Data Stream as Disjoint Intervals
Posted WhoDreamsSky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于352[LeetCode] Data Stream as Disjoint Intervals的主要内容,如果未能解决你的问题,请参考以下文章
leetcode@ [352] Data Stream as Disjoint Intervals (Binary Search & TreeSet)
[leetcode]352. Data Stream as Disjoint Intervals
352. Data Stream as Disjoint Intervals
352. Data Stream as Disjoint Interval