-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0295-find-median-from-data-stream.cpp
66 lines (56 loc) · 1.54 KB
/
0295-find-median-from-data-stream.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
/*
Implement data structure that gets the median from a data stream
Max heap of lower values & min heap of higher values, access to mids
Time: O(log n) + O(1)
Space: O(n)
*/
class MedianFinder {
public:
MedianFinder() {
}
void addNum(int num) {
if (lower.empty()) {
lower.push(num);
return;
}
if (lower.size() > higher.size()) {
if (lower.top() > num) {
higher.push(lower.top());
lower.pop();
lower.push(num);
} else {
higher.push(num);
}
} else {
if (num > higher.top()) {
lower.push(higher.top());
higher.pop();
higher.push(num);
} else {
lower.push(num);
}
}
}
double findMedian() {
double result = 0.0;
if (lower.size() == higher.size()) {
result = lower.top() + (higher.top() - lower.top()) / 2.0;
} else {
if (lower.size() > higher.size()) {
result = lower.top();
} else {
result = higher.top();
}
}
return result;
}
private:
priority_queue<int> lower;
priority_queue<int, vector<int>, greater<int>> higher;
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/