leetcode 295 数据流的中位数
一看就知道要用什么花里胡哨的数据结构,就看了题解,果然用了大顶堆和小顶堆,两个堆中分别维护小于当前中位数的数和大于当前中位数的数。如果总数为奇数,则将中位数存储在小顶堆中,如果总数为偶数,则中位数为两个堆堆顶元素之和的一半。当然如果两个堆数量失衡,则需要进行调整,贴代码。
1 class MedianFinder { 2 public: 3 priority_queue<int,vector<int>,greater<int>> queMax; 4 priority_queue<int,vector<int>,less<int>> queMin; 5 MedianFinder() 6 { 7 8 } 9 10 void addNum(int num) 11 { 12 if(queMin.empty() || num<queMin.top()) 13 { 14 queMin.push(num); 15 if(queMax.size()+1<queMin.size()) 16 { 17 queMax.push(queMin.top()); 18 queMin.pop(); 19 } 20 } 21 else 22 { 23 queMax.push(num); 24 if(queMax.size()>queMin.size()) 25 { 26 queMin.push(queMax.top()); 27 queMax.pop(); 28 } 29 } 30 } 31 32 double findMedian() 33 { 34 if(queMin.size()>queMax.size()) 35 return queMin.top(); 36 else 37 return (queMin.top()+queMax.top())/2.0; 38 } 39 }; 40 41 /** 42 * Your MedianFinder object will be instantiated and called as such: 43 * MedianFinder* obj = new MedianFinder(); 44 * obj->addNum(num); 45 * double param_2 = obj->findMedian(); 46 */

浙公网安备 33010602011771号