数据流的中位数

Posted on 2019-09-02 02:31  ben_zhuback  阅读(94)  评论(0)    收藏  举报

需要注意的点:

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 };