- For example, for
arr = [2,3,4]
, the median is3
.For example, forarr = [2,3]
, the median is(2 + 3) / 2 = 2.5
. -
MedianFinder.h #ifndef MEDIANFINDER_H #define MEDIANFINDER_H #include <iostream> #include <queue> using namespace std; class MedianFinder { public: MedianFinder(); virtual ~MedianFinder(); void addNum(int num); double findMedian(); //construct Max heap and Min heap priority_queue <int> pq_max; priority_queue <int, vector<int>, greater<int>> pq_min; protected: private: }; #endif // MEDIANFINDER_H
MedianFinder.cpp #include "MedianFinder.h" MedianFinder::MedianFinder() { //ctor } MedianFinder::~MedianFinder() { //dtor } void MedianFinder::addNum(int num) { //Maintain trees: //1.Ensure that the size difference between the two trees is no more than 1; //2.Ensure that the top value of Max tree is less than the top value of the Min tree. //3.If the Max tree has longer size, compare the top value with num, if num is bigger // push num to Min tree, else push Max top value to Mine tree and pop top vale, then push // num to Man tree. //4. If the Min tree has longer size, compare the top value with num, if num is smaller // push num to Max tree, else, push Min top value to Max tree and pop top value, then push // num to Mix tree if(pq_max.size()==pq_min.size()) { if(pq_max.empty()) { pq_max.push(num); } else if(num < pq_max.top()) { pq_max.push(num); } else{ pq_min.push(num); } } else if(pq_max.size()>pq_min.size()) { if(num>pq_max.top()) { pq_min.push(num); } else { pq_min.push(pq_max.top()); pq_max.pop(); pq_max.push(num); } } else if(pq_max.size() < pq_min.size()) { if(num<pq_min.top()) { pq_max.push(num); } else { pq_max.push(pq_min.top()); pq_min.pop(); pq_min.push(num); } } } double MedianFinder::findMedian(){ //If the size of Max is equal to the size of Min tree, the Median is equal to the //average of top values of Min and Max trees. //Otherwise output the top value of the longer size tree. if(pq_max.size()==pq_min.size()) { return (pq_max.top()+pq_min.top())/2.0; } else if(pq_max.size() > pq_min.size()) { return pq_max.top(); } else { return pq_min.top(); } }
main.cpp//test #include <iostream> #include "MedianFinder.h" using namespace std; int main() { MedianFinder M; M.addNum(2); M.addNum(1); cout<<M.findMedian()<<endl; M.addNum(4); M.addNum(3); cout<<M.findMedian()<<endl; return 0; }