乱序中的中位数
维护一个最大堆和一个最小堆,最大堆中的堆顶小于最小堆中的堆顶,并且两个堆的数据数目相差最大为1。
#include <iostream> #include <vector> #include <queue> using namespace std; void addNums(int num) { priority_queue<int, vector<int>, greater<int> >big_queue; priority_queue<int, vector<int>, less<int> >small_queue; if(big_queue.size() == small_queue.size()) { if(num < big_queue.top()) big_queue.push(num); else small_queue.push(num); } else if(big_queue.size() > small_queue.size()) { if(num > big_queue.top()) small_queue.push(num); else{ small_queue.push(big_queue.top()); big_queue.pop(); big_queue.push(num); } } else if(big_queue.size() < small_queue.size()) { if(num < small_queue.top()) big_queue.push(num); else{ big_queue.push(small_queue.top()); small_queue.pop(); small_queue.push(); } } }