Created
January 22, 2019 01:12
-
-
Save kanrourou/c7017ea49a61f6744732c704a11131cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MedianFinder { | |
public: | |
/** initialize your data structure here. */ | |
MedianFinder() { | |
} | |
void addNum(int num) { | |
if(maxPQ.empty() || num <= maxPQ.top()) | |
maxPQ.push(num); | |
else | |
minPQ.push(num); | |
rebalance(); | |
} | |
double findMedian() { | |
if(maxPQ.size() > minPQ.size()) | |
return maxPQ.top(); | |
else if(maxPQ.size() < minPQ.size()) | |
return minPQ.top(); | |
else | |
return (maxPQ.top() + minPQ.top()) / 2.0; | |
} | |
private: | |
priority_queue<int> maxPQ; | |
priority_queue<int, vector<int>, greater<int>> minPQ; | |
void rebalance() | |
{ | |
if(maxPQ.size() > minPQ.size() + 1) | |
{ | |
minPQ.push(maxPQ.top()); | |
maxPQ.pop(); | |
} | |
else if(minPQ.size() > maxPQ.size() + 1) | |
{ | |
maxPQ.push(minPQ.top()); | |
minPQ.pop(); | |
} | |
} | |
}; | |
/** | |
* Your MedianFinder object will be instantiated and called as such: | |
* MedianFinder obj = new MedianFinder(); | |
* obj.addNum(num); | |
* double param_2 = obj.findMedian(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment