Skip to content

Commit 4d3f0f4

Browse files
committed
Time: 272 ms (86.05%), Space: 117.1 MB (18.23%) - LeetHub
1 parent d34038a commit 4d3f0f4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class MedianFinder {
2+
priority_queue<int> lowers;// maxheap
3+
priority_queue<int, vector<int>, greater<int>> highers;// minheap
4+
public:
5+
/** initialize your data structure here. */
6+
MedianFinder() {
7+
8+
}
9+
10+
void rebalance(){
11+
int ll = lowers.size();
12+
int hl = highers.size();
13+
14+
if(ll - hl >= 2){
15+
// lowers is higher by 2 size
16+
highers.push(lowers.top());
17+
lowers.pop();
18+
}else if(hl - ll >= 2){
19+
lowers.push(highers.top());
20+
highers.pop();
21+
}
22+
}
23+
24+
void addNum(int num) {
25+
// add the num
26+
if(lowers.size() == 0 || num <= lowers.top())
27+
lowers.push(num);
28+
else
29+
highers.push(num);
30+
// rebalance the heaps
31+
rebalance();
32+
}
33+
34+
double findMedian() {
35+
// find the median
36+
if(lowers.size() == highers.size())
37+
return (double)(lowers.top() + highers.top()) / 2;
38+
else{
39+
if(lowers.size() > highers.size())
40+
return lowers.top();
41+
else
42+
return highers.top();
43+
}
44+
45+
return 0.0;
46+
}
47+
};
48+
49+
/**
50+
* Your MedianFinder object will be instantiated and called as such:
51+
* MedianFinder* obj = new MedianFinder();
52+
* obj->addNum(num);
53+
* double param_2 = obj->findMedian();
54+
*/

0 commit comments

Comments
 (0)