File tree 1 file changed +9
-10
lines changed
find_median_from_data_stream
1 file changed +9
-10
lines changed Original file line number Diff line number Diff line change 1
1
#include < vector>
2
2
#include < iostream>
3
+ #include < priority_queue>
4
+ #include < functional>
3
5
using namespace std ;
4
6
5
7
class Heap {
@@ -61,10 +63,9 @@ int min(int i, int j) {
61
63
}
62
64
63
65
class 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;
66
68
public:
67
- MedianFinder (): max_heap(Heap(max)), min_heap(Heap(min)){}
68
69
// Adds a number into the data structure.
69
70
void addNum (int num) {
70
71
if (max_heap.empty () || num <= max_heap.top ()) {
@@ -73,23 +74,21 @@ class MedianFinder {
73
74
min_heap.push (num);
74
75
}
75
76
if (max_heap.size () > min_heap.size ()+1 ){
76
- int top = max_heap.pop ();
77
+ int top = max_heap.top ();
78
+ max_heap.pop ();
77
79
min_heap.push (top);
78
80
}
79
81
if (min_heap.size () > max_heap.size ()) {
80
- int top = min_heap.pop ();
82
+ int top = min_heap.top ();
83
+ min_heap.pop ();
81
84
max_heap.push (top);
82
85
}
83
86
return ;
84
87
}
85
88
86
89
// Returns the median of current data stream
87
90
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 ();
93
92
}
94
93
};
95
94
You can’t perform that action at this time.
0 commit comments