File tree Expand file tree Collapse file tree 1 file changed +9
-10
lines changed
find_median_from_data_stream Expand file tree Collapse file tree 1 file changed +9
-10
lines changed Original file line number Diff line number Diff line change 11#include < vector>
22#include < iostream>
3+ #include < priority_queue>
4+ #include < functional>
35using namespace std ;
46
57class Heap {
@@ -61,10 +63,9 @@ int min(int i, int j) {
6163}
6264
6365class MedianFinder {
64- Heap max_heap;
65- Heap min_heap;
66+ priority_queue< int > max_heap;
67+ priority_queue< int , vector< int >, greater< int >> min_heap;
6668public:
67- MedianFinder (): max_heap(Heap(max)), min_heap(Heap(min)){}
6869 // Adds a number into the data structure.
6970 void addNum (int num) {
7071 if (max_heap.empty () || num <= max_heap.top ()) {
@@ -73,23 +74,21 @@ class MedianFinder {
7374 min_heap.push (num);
7475 }
7576 if (max_heap.size () > min_heap.size ()+1 ){
76- int top = max_heap.pop ();
77+ int top = max_heap.top ();
78+ max_heap.pop ();
7779 min_heap.push (top);
7880 }
7981 if (min_heap.size () > max_heap.size ()) {
80- int top = min_heap.pop ();
82+ int top = min_heap.top ();
83+ min_heap.pop ();
8184 max_heap.push (top);
8285 }
8386 return ;
8487 }
8588
8689 // Returns the median of current data stream
8790 double findMedian () {
88- if (max_heap.size () == min_heap.size ())
89- return ((max_heap.top ()+min_heap.top ())/2.0 );
90- if (max_heap.size () > min_heap.size ())
91- return max_heap.top ();
92- return min_heap.top ();
91+ return max_heap.size () == min_heap.size () ? (max_heap.top ()+min_heap.top ())/2.0 : max_heap.top ();
9392 }
9493};
9594
You can’t perform that action at this time.
0 commit comments