Skip to content

Commit 80ae292

Browse files
Create find_median_from_stream.cpp
1 parent e9dc381 commit 80ae292

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

find_median_from_stream.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class MedianFinder {
2+
public:
3+
priority_queue<int> maxHeap;
4+
priority_queue<int, vector<int>, greater<> > minHeap;
5+
/*
6+
1) store first half in maxheap, second half in minheap
7+
2) maxheap can have 1 element more than minheap
8+
*/
9+
void addNum(int num) {
10+
maxHeap.push(num);
11+
minHeap.push(maxHeap.top());
12+
maxHeap.pop();
13+
14+
if(minHeap.size() > maxHeap.size()){
15+
maxHeap.push(minHeap.top());
16+
minHeap.pop();
17+
}
18+
}
19+
double findMedian() {
20+
if(maxHeap.size() == minHeap.size()) {
21+
return (maxHeap.top() + minHeap.top()) / 2.0;
22+
}
23+
return maxHeap.top();
24+
}
25+
};

0 commit comments

Comments
 (0)