给定一个非负整数的数据流输入 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]
进阶:
如果有很多合并,并且与数据流的大小相比,不相交间隔的数量很小,该怎么办?
/**
* 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. */
SummaryRanges() {
}
void addNum(int val) {
Interval cur(val, val);
vector<Interval> res;
int pos = 0;
for (auto a : v) {
if (cur.end + 1 < a.start) {
res.push_back(a);
} else if (cur.start > a.end + 1) {
res.push_back(a);
++pos;
} else {
cur.start = min(cur.start, a.start);
cur.end = max(cur.end, a.end);
}
}
res.insert(res.begin() + pos, cur);
v = res;
}
vector<Interval> getIntervals() {
return v;
}
private:
vector<Interval> v;
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/