原题地址:https://leetcode-cn.com/problems/data-stream-as-disjoint-intervals/submissions/
题目描述:
给定一个非负整数的数据流输入 a1,a2,…,an,…,将到目前为止看到的数字总结为不相交的间隔列表。
例如,假设数据流中的整数为 1,3,7,2,6,…,每次的总结为:
[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]
进阶:
如果有很多合并,并且与数据流的大小相比,不相交间隔的数量很小,该怎么办?
提示:
特别感谢 @yunhong 提供了本问题和其测试用例。
解题方案:
首先使用的是最简单的办法,直接遍历一遍,没有用到二叉搜索树:
/**
* 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 SummaryRanges {
public:
/** Initialize your data structure here. */
vector ans;
SummaryRanges() {
}
void addNum(int val) {
Interval v(val, val);
vector tmp;
if(!ans.size()){
tmp.push_back(v);
}
else{
int flag = 0;
for(auto a : ans){
if(a.end == v.start - 1){
v.start = a.start;
}
else if(a.start == v.end + 1){
v.end = a.end;
}
else if(a.end < v.start - 1){
tmp.push_back(a);
}
else if(a.start > v.end + 1){
if(!flag){
tmp.push_back(v);
flag = 1;
}
tmp.push_back(a);
}
else{
flag = 1;
tmp.push_back(a);
}
}
if(!flag)
tmp.push_back(v);
}
ans = tmp;
}
vector getIntervals() {
return ans;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector param_2 = obj->getIntervals();
*/
学习时间最短的算法:
/**
* 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 SummaryRanges {
public:
/** Initialize your data structure here. */
int n=0;
vector A;
SummaryRanges() {
}
void addNum(int val) {
int l=0,r=n-1,mid;
Interval B;
while(l<=r){
mid=(l+r)>>1;
if(A[mid].start>val) r=mid-1;
else if(A[mid].endval){
B.start=B.end=val;
A.insert(A.begin(),B);
n++;
return;
}
else
A[l].start=val;
}
if(A[r].end+1val){
B.start=B.end=val;
A.insert(A.begin()+r+1,B);
n++;
return;
}
else {
if(A[l].start-1==val)
A[l].start=val;
}
}
else{
A[r].end=val;
if(l getIntervals() {
return A;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges* obj = new SummaryRanges();
* obj->addNum(val);
* vector param_2 = obj->getIntervals();
*/