题目
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]
Follow up:
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream’s size?
思路
题目要求是合并多,而且不连续的interval相比输入的数据量比较少,所以这边选择用链表来作为存储的数据结构。插入时基本就是按要求来,该合并合并该插入新的就插入新的,输出时遍历一遍就可以。
代码
/**
* 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:
struct Node{
Interval intv;
Node *next;
Node() : intv(-2, -2), next(NULL) {}
Node(int s, int e) : intv(s, e), next(NULL) {}
};
Node *pBegin;
/** Initialize your data structure here. */
SummaryRanges() {
pBegin = new Node();
}
void addNum(int val) {
Node *pCur = pBegin, *pNext, *pTemp;
while((pCur->intv).end - val < -1){
if(pCur->next == NULL){
pCur->next = new Node(val, val);
return;
}
pNext = pCur->next;
if((pNext->intv).start >= val){
if((pNext->intv).start <= val+1){
(pNext->intv).start = val;
return;
}
else{
pTemp = pCur->next;
pCur->next = new Node(val, val);
pCur->next->next = pTemp;
return;
}
}
else if((pNext->intv).end >= val)
return;
pCur = pCur->next;
}
(pCur->intv).end = val;
if(pCur->next == NULL)
return;
pNext = pCur->next;
if((pNext->intv).start - val == 1){
(pCur->intv).end = (pNext->intv).end;
pCur->next = pNext->next;
delete[] pNext;
} else
(pCur->intv).end = val;
return;
}
vector<Interval> getIntervals() {
Node *pCur = pBegin->next;
vector<Interval> vOut;
while(pCur != NULL){
vOut.push_back(pCur->intv);
pCur = pCur->next;
}
return vOut;
}
};
感想
写代码的时候感觉思路比较乱,想不大清楚判断的顺序应该怎么写比较好,最后莫名其妙就通过了,但代码看着就很丑。。。等啥时候有时间再看看怎么调整吧。另外,如果题目的要求反过来,合并比较少分开的interval很多的话思路应该要改变,主要的时间消耗应该会在搜索上,那可能一些近似平衡的二叉树结构会更快一下吧。