-
Notifications
You must be signed in to change notification settings - Fork 0
/
295.数据流的中位数.cpp
116 lines (105 loc) · 2.54 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*
* @lc app=leetcode.cn id=295 lang=cpp
*
* [295] 数据流的中位数
* 用大顶堆和小顶堆来实现,
* 还有其他实现方式 待研究
*
* 提交不能通过问题:答案是一样的,浮点的位数不一致
*/
// @lc code=start
#include <queue>
#include <vector>
using namespace std;
class MedianFinder
{
public:
priority_queue<int, vector<int>, greater<int>> smallQueue;
priority_queue<int, vector<int>, less<int>> bigQueue;
/** initialize your data structure here. */
MedianFinder()
{
}
void addNum(int num)
{
if (smallQueue.empty())
{
smallQueue.push(num);
return;
}
/* if (num > smallQueue.top())
smallQueue.push(num);
else
bigQueue.push(num);
if (!bigQueue.empty() && bigQueue.size() - smallQueue.size() > 1)
{
smallQueue.push(bigQueue.top());
bigQueue.pop();
}
if (smallQueue.size() - bigQueue.size() > 1)
{
bigQueue.push(smallQueue.top());
smallQueue.pop();
} */
if (smallQueue.size() > bigQueue.size())
{
if (num > smallQueue.top())
{
bigQueue.push(smallQueue.top());
smallQueue.pop();
smallQueue.push(num);
}
else
{
bigQueue.push(num);
}
}
else if (smallQueue.size() < bigQueue.size())
{
if (num < smallQueue.top())
{
smallQueue.push(bigQueue.top());
bigQueue.pop();
bigQueue.push(num);
}
else
{
smallQueue.push(num);
}
}
else
{
if (num < smallQueue.top())
{
bigQueue.push(num);
}
else
{
smallQueue.push(num);
}
}
}
double findMedian()
{
int diff = smallQueue.size() - bigQueue.size();
if (diff > 0)
{
return smallQueue.top();
}
else if (diff < 0)
{
return bigQueue.top();
}
else
{
return static_cast<double>(smallQueue.top() + bigQueue.top()) / 2;
}
}
};
/**
* 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