-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path295.数据流的中位数.cpp
64 lines (60 loc) · 1.24 KB
/
295.数据流的中位数.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
62
63
64
/*
* @lc app=leetcode.cn id=295 lang=cpp
*
* [295] 数据流的中位数
*/
#include "a_header.h"
// @lc code=start
class MedianFinder
{
private:
priority_queue<int, vector<int>, less<int>> Min;
priority_queue<int, vector<int>, greater<int>> Max;
public:
MedianFinder()
{
}
void addNum(int num)
{
if (Min.empty() || num <= findMedian())
{
Min.push(num);
if (Max.size() + 1 < Min.size())
{
Max.push(Min.top());
Min.pop();
}
}
else
{
Max.push(num);
if (Max.size() > Min.size() + 1)
{
Min.push(Max.top());
Max.pop();
}
}
}
double findMedian()
{
if (Max.size() == Min.size())
{
return (Max.top() + Min.top()) / 2.0;
}
else if (Max.size() > Min.size())
{
return Max.top();
}
else
{
return Min.top();
}
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
// @lc code=end