295. 数据流的中位数

中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。

例如,

[2,3,4] 的中位数是 3

[2,3] 的中位数是 (2 + 3) / 2 = 2.5

设计一个支持以下两种操作的数据结构:

void addNum(int num) - 从数据流中添加一个整数到数据结构中。
double findMedian() - 返回目前所有元素的中位数。
示例:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-median-from-data-stream
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 1 class MedianFinder {
 2 public:
 3     /** initialize your data structure here. */
 4     //用两个堆
 5     //一个大顶堆 一个小顶堆
 6     //大顶堆存小的一半 小顶堆存大的一半
 7     //大顶堆堆顶为小的一半中最大的 小顶堆堆顶是大的一半中最小的
 8     //先判断元素该入哪个堆 再平衡两个堆的大小
 9     //若大小顶堆数量相同
10     //  中位数是(top1()+top2())/2
11     //否找中位数是 数量大的一个堆的堆顶
12     priority_queue<int> big_pq;
13     priority_queue<int,vector<int>,greater<int>> small_pq;
14     MedianFinder() {}
15     void addNum(int num) {
16         if(!big_pq.size()&&!small_pq.size())
17             big_pq.push(num);
18         else if(num<=big_pq.top())
19         {
20           big_pq.push(num);
21           while(big_pq.size()>small_pq.size()+1)
22           {
23             small_pq.push(big_pq.top());
24             big_pq.pop();
25           }
26         }
27         else
28         {
29             small_pq.push(num);
30             while(small_pq.size()>big_pq.size()+1)
31             {
32                 big_pq.push(small_pq.top());
33                 small_pq.pop();
34             }
35         }
36     }
37     double findMedian() {
38         if(big_pq.size()==small_pq.size())
39         {
40             if(!big_pq.empty())
41                 return (big_pq.top()+small_pq.top())*0.5;
42             else
43                 return 0;
44         }
45         else if(big_pq.size()>small_pq.size())
46             return big_pq.top();
47         else return small_pq.top();
48     }
49 };
50 
51 /**
52  * Your MedianFinder object will be instantiated and called as such:
53  * MedianFinder* obj = new MedianFinder();
54  * obj->addNum(num);
55  * double param_2 = obj->findMedian();
56  */

 

posted @ 2020-07-09 16:03  lancelee98  阅读(117)  评论(0编辑  收藏  举报