-
Notifications
You must be signed in to change notification settings - Fork 28
/
Data_Stream_as_Disjoint_Intervals.cpp
67 lines (64 loc) · 2.07 KB
/
Data_Stream_as_Disjoint_Intervals.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* 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 {
class Compare {
public:
bool operator()(Interval const& lhs, Interval const& rhs) {
if(lhs.start == rhs.start) {
return lhs.end < rhs.end;
}
return lhs.start < rhs.start;
}
};
set<Interval, Compare> intervalSet;
public:
/** Initialize your data structure here. */
SummaryRanges() {
intervalSet = set<Interval, Compare>();
}
void addNum(int val) {
set<Interval>::iterator iter = (intervalSet.insert(Interval(val, val))).first;
while(iter != intervalSet.begin() and iter->start == val) {
--iter;
}
set<Interval>::iterator nxt = iter;
++nxt;
int start = val, end = val;
if(nxt != intervalSet.end() and iter->end + 1 >= nxt->start) {
start = iter->start;
end = max(iter->end, nxt->end);
intervalSet.erase(iter);
intervalSet.erase(nxt);
intervalSet.insert(Interval(start, end));
}
iter = intervalSet.find(Interval(start, end));
nxt = iter; ++nxt;
while(nxt != intervalSet.end() and iter->end + 1 >= nxt->start) {
start = iter->start;
end = max(iter->end, nxt->end);
nxt = intervalSet.erase(iter);
nxt = intervalSet.erase(nxt);
intervalSet.insert(Interval(start, end));
iter = intervalSet.find(Interval(start, end));
nxt = iter; ++nxt;
}
}
vector<Interval> getIntervals() {
vector<Interval> result(intervalSet.size());
copy(intervalSet.begin(), intervalSet.end(), result.begin());
return result;
}
};
/**
* Your SummaryRanges object will be instantiated and called as such:
* SummaryRanges obj = new SummaryRanges();
* obj.addNum(val);
* vector<Interval> param_2 = obj.getIntervals();
*/