Created
July 10, 2019 16:23
-
-
Save yangpeng-chn/97e763a2e07a4ddc6ff0df70c6bb7a1b to your computer and use it in GitHub Desktop.
Two heaps
This file contains 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 { | |
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