剑指offer——43数据流中的中位数

题目描述

如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
 
题解:
  目前想不出更好的方法,待续更新。。。
 
  
 1 class Solution {
 2 private:
 3     vector<int> min;
 4     vector<int> max;
 5 public:
 6         void Insert(int num)
 7         {
 8            int size=min.size()+max.size();
 9            if((size&1)==0)
10            {
11               if(max.size()>0 && num<max[0])
12               {
13                  max.push_back(num);
14                  push_heap(max.begin(),max.end(),less<int>());
15                  num=max[0];
16                  pop_heap(max.begin(),max.end(),less<int>());
17                  max.pop_back();
18               }
19               min.push_back(num);
20               push_heap(min.begin(),min.end(),greater<int>());
21            }
22            else
23            {
24               if(min.size()>0 && num>min[0])
25               {
26                 min.push_back(num);
27                  push_heap(min.begin(),min.end(),greater<int>());
28                  num=min[0];
29                  pop_heap(min.begin(),min.end(),greater<int>());
30                  min.pop_back();
31               }
32               max.push_back(num);
33               push_heap(max.begin(),max.end(),less<int>());
34            }   
35         }
36          
37         double GetMedian()
38         {
39             int size=min.size()+max.size();
40             if(size<=0)
41                 return 0;
42             if((size&1)==0)
43                 return (max[0]+min[0])/2.0;
44             else
45                 return min[0];
46         }
47  
48   
49 };

 

posted @ 2019-10-16 23:29  自由之翼Az  阅读(113)  评论(0编辑  收藏  举报