-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_STO_0041_MedianFinder.cc
58 lines (53 loc) · 1.05 KB
/
Problem_STO_0041_MedianFinder.cc
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
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class MedianFinder
{
private:
priority_queue<int, vector<int>, std::less<int>> min; // 大根堆
priority_queue<int, vector<int>, std::greater<int>> max; // 小根堆
public:
/** initialize your data structure here. */
MedianFinder() {}
void addNum(int num)
{
if (min.empty() || num < min.top())
{
min.push(num);
if (min.size() > max.size() + 1)
{
int cur = min.top();
min.pop();
max.push(cur);
}
}
else
{
max.push(num);
if (max.size() > min.size())
{
int cur = max.top();
max.pop();
min.push(cur);
}
}
}
double findMedian()
{
if (min.size() > max.size())
{
return min.top();
}
else
{
return (min.top() + max.top()) / 2.0;
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/