首页 > 其他 > 详细

数据流中的中位数

时间:2016-05-08 15:17:28      阅读:205      评论:0      收藏:0      [点我收藏+]

 

 1 class Solution {
 2 public:
 3     void Insert(int num)
 4     {
 5         if((count&1) == 0)
 6         {
 7             if(max.size()>0 &&num < max.front())
 8             {
 9                 max.push_back(num);
10                 push_heap(max.begin(), max.end(), less<int>());
11                 num = max.front();
12                 pop_heap(max.begin(), max.end(), less<int>());
13                 max.pop_back();
14             }
15             min.push_back(num);
16             push_heap(min.begin(), min.end(), greater<int>());
17         }
18         else
19         {
20             if(min.size()>0 &&num > min.front())
21             {
22                 min.push_back(num);
23                 push_heap(min.begin(), min.end(), greater<int>());
24                 num=min.front();
25                 pop_heap(min.begin(), min.end(), greater<int>());
26                 min.pop_back();
27             }
28             max.push_back(num);
29             push_heap(max.begin(), max.end(), less<int>());
30              
31         }
32         ++count;
33          
34     }
35  
36     double GetMedian()
37     {
38         if(count == 0)
39             return -1;
40         if((count &1) == 0)
41             return ((double)max.front() + (double)min.front())/2;
42         else return min.front();
43     }
44 private:
45     vector<int> max;
46     vector<int> min;
47     int count = 0;
48  
49 };

 

数据流中的中位数

原文:http://www.cnblogs.com/daocaorenblog/p/5470628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!