File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
19 - Heap Data Structure Problems/16 - Find Median in a Stream Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution
2+ {
3+ public:
4+ priority_queue<int > maxHeap;
5+ priority_queue<int , vector<int >, greater<int >> minHeap;
6+
7+ void insertHeap (int &x)
8+ {
9+ if (maxHeap.size () == 0 || x < maxHeap.top ()) maxHeap.push (x);
10+ else minHeap.push (x);
11+
12+ balanceHeaps ();
13+ }
14+
15+ void balanceHeaps (){
16+ if (maxHeap.size () > minHeap.size () + 1 ){
17+ minHeap.push (maxHeap.top ());
18+ maxHeap.pop ();
19+ }else if (minHeap.size () > maxHeap.size ()){
20+ maxHeap.push (minHeap.top ());
21+ minHeap.pop ();
22+ }
23+ }
24+
25+ double getMedian (){
26+ if (maxHeap.size () == minHeap.size ()) return (minHeap.top () + maxHeap.top ()) / 2.0 ;
27+ else return maxHeap.top ();
28+ }
29+ };
You can’t perform that action at this time.
0 commit comments