-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdui.cpp
More file actions
47 lines (44 loc) · 1011 Bytes
/
dui.cpp
File metadata and controls
47 lines (44 loc) · 1011 Bytes
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
#include <iostream>
#include <queue>
#include <vector>
class MedianFinder
{
private:
std::priority_queue<int> maxHeap; // max heap for the left half
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap; // min heap for the right half
public:
MedianFinder(){
}
void addNum(int num)
{
maxHeap.push(num);
minHeap.push(maxHeap.top());
maxHeap.pop();
if (maxHeap.size() < minHeap.size())
{
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
double findMedian()
{
if (maxHeap.size() > minHeap.size())
{
return maxHeap.top();
}
else
{
return (maxHeap.top() + minHeap.top()) / 2.0;
}
}
};
int main()
{
MedianFinder mf;
mf.addNum(1);
mf.addNum(2);
std::cout << mf.findMedian() << std::endl; // Output: 1.5
mf.addNum(3);
std::cout << mf.findMedian() << std::endl; // Output: 2.0
return 0;
}