-
Notifications
You must be signed in to change notification settings - Fork 0
/
Selecting Median from Data Streams
66 lines (59 loc) · 1.58 KB
/
Selecting Median from Data Streams
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
class MedianFinder {
public:
priority_queue<int>max_heap;
priority_queue<int,vector<int>,greater<>>min_heap;
MedianFinder() {
}
void addNum(int num) {
if(max_heap.size()==0&&min_heap.size()==0)
max_heap.push(num);
else if(max_heap.size()>0)
{
if(max_heap.top()<=num)
min_heap.push(num);
else
max_heap.push(num);
if((max_heap.size()-min_heap.size())<=1)
return;
if(max_heap.size()>min_heap.size())
{
int top=max_heap.top();
max_heap.pop();
min_heap.push(top);
}
else
{
int top=min_heap.top();
min_heap.pop();
max_heap.push(top);
}
}
return;
}
double findMedian() {
double d;
if(max_heap.size()==min_heap.size())
{
double d1= max_heap.top();
double d2 = min_heap.top();
d = (d1+d2)/2.0;
return d;
}
else if(max_heap.size()>min_heap.size())
{
double top=max_heap.top();
return top;
}
else
{
double top=min_heap.top();
return top;
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/