题目:
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路:
可以参考链接 数据流中的中位数:https://www.jianshu.com/p/f7e2ed52052d
1 #include <iostream> 2 #include <vector> 3 #include <queue> 4 5 using namespace std; 6 7 //数据流的中位数 8 class Solution { 9 private: 10 int count = 0; 11 priority_queue<int,vector<int>> max_heap; //最大堆 12 priority_queue<int,vector<int>,greater<int>> min_heap; //最小堆 13 14 public: 15 void Insert(int num) 16 { 17 count++; 18 //第偶数个->插入最小堆; 19 if((count & 1)==0){ //偶数 判断偶数的高效写法 20 min_heap.push(num); 21 if(!max_heap.empty() && max_heap.top()>num) //如果要插入的新元素比最大堆的堆顶要小 22 { 23 min_heap.pop(); 24 25 int temp = max_heap.top(); 26 max_heap.pop(); 27 min_heap.push(temp); //最大堆的堆顶插入最小堆 28 29 max_heap.push(num); //新元素插入最大堆 30 } 31 } 32 //第奇数个->插入最大堆; 33 else{ 34 max_heap.push(num); 35 if(!min_heap.empty() && min_heap.top() < num){ //如果要插入的新元素比最小堆的堆顶要大 36 max_heap.pop(); 37 38 int temp = min_heap.top(); 39 min_heap.pop(); 40 max_heap.push(temp); //最小堆的堆顶插入最大堆 41 42 min_heap.push(num); //新元素插入最小堆 43 } 44 } 45 //以上的方式可以一直维持中位数在最小堆和最大堆的堆顶,如果个数为偶数,则为两堆堆顶的平均数,如果个数为奇数,则为最大堆堆顶; 46 } 47 48 double GetMedian() 49 { 50 double res; 51 if((count &1) == 0){ //偶数 52 res = ((double)max_heap.top()+(double)min_heap.top())/2; 53 } 54 else{ 55 res = max_heap.top(); 56 } 57 58 return res; 59 } 60 61 }; 62 63 int main() 64 { 65 Solution sol; 66 vector<int> nums={5,2,3,4,1,6,7,0,8,5}; 67 for(int i =0; i<nums.size();i++){ 68 sol.Insert(nums[i]); 69 } 70 cout<<sol.GetMedian()<<endl; 71 }
原文:https://www.cnblogs.com/grooovvve/p/12367724.html