码迷,mamicode.com
首页 > 其他好文 > 详细

数据流的中位数

时间:2019-09-02 09:55:34      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:less   int   class   中位数   ret   大根堆   priority   元素   return   

需要注意的点:

priority_queue  不会拼 真丢人

默认是大根堆  priority_queue<int,vector<int>,less<int>>  大根堆

                       priority_queue<int,vector<int>,greater<int>> 小根堆

 

 1 class Solution {
 2 public:
 3     //思路 用一个大顶堆存前一半的数据  用一个小顶堆存后一半的数据
 4     /*
 5     逻辑:
 6     大顶堆是空  直接加入
 7     大顶堆不是空  和堆顶元素比较
 8     如果比堆顶元素大  加入小顶堆   否则加入大顶堆
 9     如果大顶堆的元素个数比小顶堆多两个  将大顶堆堆顶移动到小顶堆  重新调整
10     如果小顶堆的元素比大顶堆多一个 小顶堆堆顶移动到大顶堆
11     
12     取出中位数
13     如果两个堆元素个数一样  取两个堆顶 求和相除
14     如果大顶堆堆元素个数多  取大顶堆堆顶
15     */
16     priority_queue<int> maxheap;  //默认大根堆
17     priority_queue<int,vector<int>,greater<int>> minheap;
18     void Insert(int num) //O(logN)
19     {
20         if(maxheap.empty())
21             maxheap.push(num);
22         else{
23             if(num > maxheap.top())
24                 minheap.push(num);
25             else
26                 maxheap.push(num);
27             if(minheap.size() == maxheap.size()+1){
28                 maxheap.push(minheap.top());
29                 minheap.pop();
30             }
31             
32             if(maxheap.size() == minheap.size()+2){
33                 minheap.push(maxheap.top());
34                 maxheap.pop();
35             }
36         }
37         
38     }
39 
40     double GetMedian() // O(1)
41     { 
42         return maxheap.size() == minheap.size() ? (maxheap.top()+minheap.top())/2.0 : maxheap.top();
43     }
44 
45 };

 

数据流的中位数

标签:less   int   class   中位数   ret   大根堆   priority   元素   return   

原文地址:https://www.cnblogs.com/znshao/p/11444474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!