Use two priority queues, maxHeap and minHeap, to record numbers less than the median and numbers greater than or equal to the median respectively.
Min-heap, stores the larger half (so the top element is the smallest in the larger half, i.e., closest to the center)
Max-heap, stores the smaller half (so the top element is the largest in the smaller half, i.e., closest to the center)
When the total number of added numbers is odd, minHeap has one more number than maxHeap, and the median is the top of minHeap. When the total number is even, both priority queues have the same number of elements, and the median is the average of their tops. In particular, when the total number is 0, we add num to minHeap.
classMedianFinder { private: priority_queue<int, vector<int>, std::less<int> > max_heap; // store the smaller part priority_queue<int, vector<int>, std::greater<int> > min_heap; // store the larger part
public: MedianFinder() { }
voidaddNum(int num) { if (max_heap.empty()) { max_heap.push(num); return; }
if ((max_heap.size() + min_heap.size()) % 2 != 0) { // odd number int curr_mid = max_heap.top(); if (num >= curr_mid) { min_heap.push(num); } else { min_heap.push(curr_mid); max_heap.pop(); max_heap.push(num); }
} else { //even number if (num <= min_heap.top()) { max_heap.push(num); } else { max_heap.push(min_heap.top()); min_heap.pop(); min_heap.push(num); } } }