-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetMedianInDataStream.cpp
More file actions
77 lines (69 loc) · 1.41 KB
/
GetMedianInDataStream.cpp
File metadata and controls
77 lines (69 loc) · 1.41 KB
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
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct mycomp {
bool reverse;
mycomp(const bool & _reverse = false) {
reverse = _reverse;
}
bool operator () (const int &a, const int & b) {
if(reverse) {
return a > b;
} else {
return a < b;
}
}
};
typedef priority_queue<int, vector<int>, mycomp> pq;
pq r_min_pq(mycomp(true));
pq l_max_pq;
void feedData(const int &num) {
if(r_min_pq.empty()) { // put in right queue first
r_min_pq.push(num);
} else if (l_max_pq.empty()) {
int r = r_min_pq.top();
if(num > r) {
r_min_pq.pop();
r_min_pq.push(num);
l_max_pq.push(r);
} else {
l_max_pq.push(num);
}
} else {
int l = l_max_pq.top();
int r = r_min_pq.top();
if(num < l) {
if(l_max_pq.size() > r_min_pq.size()) {
r_min_pq.push(l_max_pq.top());
l_max_pq.pop();
}
l_max_pq.push(num);
} else if (num < r) {
if(l_max_pq.size() > r_min_pq.size()) {
r_min_pq.push(num);
} else {
l_max_pq.push(num);
}
} else {
if(r_min_pq.size() > l_max_pq.size()) {
l_max_pq.push(r_min_pq.top());
r_min_pq.pop();
}
r_min_pq.push(num);
}
}
}
double getMedian() {
if(l_max_pq.size() < r_min_pq.size()) {
return r_min_pq.top();
} else if(r_min_pq.size() > l_max_pq.size()) {
return l_max_pq.top();
} else {
if(l_max_pq.size() == 0) return 0;
return (l_max_pq.top() + r_min_pq.top())/2.0;
}
}
int main() {
return 0;
}