0%

剑指 Offer 41. 数据流中的中位数

剑指 Offer 41. 数据流中的中位数

参考295. Find Median from Data Stream

两个优先级队列

有点忘了

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
class MedianFinder {
public:
/** initialize your data structure here. */
MedianFinder() {

}

void addNum(int num) {
if(q1.size() == q2.size())
{
q1.push(num);
q2.push(q1.top());
q1.pop();
}else
{
q2.push(num);
q1.push(q2.top());
q2.pop();
}

}

double findMedian() {
if(q1.size() != q2.size())
return q2.top();
else
return (q1.top() + q2.top()) / 2.0;
}
private:
priority_queue<int, vector<int>, std::greater<int>> q1;
priority_queue<int> q2;
};

/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/