find-median-from-data-stream 1.0.0
Find Median from Data Stream
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7private:
8 priority_queue<int> max_heap;
9 priority_queue<int, vector<int>, greater<int>> min_heap;
10
11public:
13
14 void addNum(int num)
15 {
16 if (max_heap.empty() || num <= max_heap.top())
17 {
18 cout << "adding " << num << " to max heap" << endl;
19 max_heap.push(num);
20 }
21 else
22 {
23 cout << "adding " << num << " to min heap" << endl;
24 min_heap.push(num);
25 }
26
27 // balancing heaps
28 if (max_heap.size() > min_heap.size() + 1)
29 {
30 cout << "moving " << max_heap.top() << " from max to min heap" << endl;
31 min_heap.push(max_heap.top());
32 max_heap.pop();
33 }
34 else if (min_heap.size() > max_heap.size())
35 {
36 cout << "moving " << min_heap.top() << " from min to max heap" << endl;
37 max_heap.push(min_heap.top());
38 min_heap.pop();
39 }
40 }
41
42 double findMedian()
43 {
44 if (max_heap.size() == min_heap.size())
45 return (max_heap.top() + min_heap.top()) / 2.0;
46 else
47 return max_heap.top();
48 }
49};
50
51int main()
52{
53 MedianFinder* obj = new MedianFinder();
54 obj->addNum(1);
55 obj->addNum(2);
56 double param_2 = obj->findMedian();
57 cout << param_2 << endl;
58 obj->addNum(3);
59 param_2 = obj->findMedian();
60 cout << param_2 << endl;
61 delete obj;
62 return 0;
63}
MedianFinder()
Definition main.cpp:12
void addNum(int num)
Definition main.cpp:14
priority_queue< int > max_heap
Definition main.cpp:8
double findMedian()
Definition main.cpp:42
priority_queue< int, vector< int >, greater< int > > min_heap
Definition main.cpp:9
int main()
Definition main.cpp:51