forked from Athe1stB/leetcode_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindMedianFromDataStream.cpp
61 lines (52 loc) · 1.31 KB
/
FindMedianFromDataStream.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
class MedianFinder {
public:
/** initialize your data structure here. */
priority_queue<int> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
int cnt = 0;
MedianFinder() {
while(!maxHeap.empty())
maxHeap.pop();
while(!minHeap.empty())
minHeap.pop();
cnt = 0;
}
void balance()
{
if(minHeap.size()>maxHeap.size())
maxHeap.push(minHeap.top()),
minHeap.pop();
if(maxHeap.size() == minHeap.size()+2)
minHeap.push(maxHeap.top()),
maxHeap.pop();
}
void addNum(int num) {
if(maxHeap.empty())
maxHeap.push(num);
else
{
if(maxHeap.top()>=num)
maxHeap.push(num);
else
minHeap.push(num);
balance();
}
cnt++;
}
double findMedian() {
if(cnt&1)
return maxHeap.top();
else
{
double ans = minHeap.top()+maxHeap.top();
ans/=2;
return ans;
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/