数据流中的中位数

 

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

 

posted on 2016-05-08 14:43  RenewDo  阅读(113)  评论(0编辑  收藏  举报

导航