Skip to content

Commit 1902ee7

Browse files
authored
Create main.cpp
1 parent 1280076 commit 1902ee7

File tree

1 file changed

+29
-0
lines changed
  • 19 - Heap Data Structure Problems/16 - Find Median in a Stream

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
};

0 commit comments

Comments
 (0)