Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Created July 10, 2019 16:23
Show Gist options
  • Save yangpeng-chn/97e763a2e07a4ddc6ff0df70c6bb7a1b to your computer and use it in GitHub Desktop.
Save yangpeng-chn/97e763a2e07a4ddc6ff0df70c6bb7a1b to your computer and use it in GitHub Desktop.
Two heaps
class MedianFinder {
private:
priority_queue<int> lomax;
priority_queue<int, vector<int>, greater<int>> himin;
public:
/** initialize your data structure here. */
MedianFinder() {
}
void addNum(int num) {
lomax.push(num);
himin.push(lomax.top());
lomax.pop();
if(lomax.size() < himin.size()){
lomax.push(himin.top());
himin.pop();
}
}
double findMedian() {
return lomax.size() > himin.size() ? lomax.top() : (lomax.top() + himin.top()) * 0.5;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment