LeetCode OJ:Find Median from Data Stream(找数据流的中数)

本文介绍了一种在数据流中高效找到当前所有数值中位数的方法,通过使用最大堆和最小堆的数据结构来实现。当有新数值加入时,能够保持两个堆之间的平衡,并据此快速计算出中位数。

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

Examples: 

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

For example:

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

如上,可以维护一个最大堆以及一个最小堆,如果小堆数的数量大于大堆数量。那么可以把小堆中的最小值返还给大堆。(注意这个值相当于大堆中的最大者,因为小堆中的值都是大堆中转移过去的)。代码如下:

 1 class MedianFinder {
 2 public:
 3 
 4     // Adds a number into the data structure.
 5     void addNum(int num) {
 6         maxHeap.push(num);
 7         int tmp = maxHeap.top();
 8         maxHeap.pop();    
 9         minHeap.push(tmp);
10         if(minHeap.size() > maxHeap.size()){
11             tmp = minHeap.top();
12             minHeap.pop();
13             maxHeap.push(tmp);
14         }
15     }
16 
17     // Returns the median of current data stream
18     double findMedian() {
19         int m = maxHeap.size();
20         int n = minHeap.size();
21         if(m > n)
22             return maxHeap.top()/1.0;
23         else
24             return (maxHeap.top() + minHeap.top())/2.0;
25     }
26 private:
27     priority_queue<int, vector<int>, greater<int>> maxHeap;
28     priority_queue<int, vector<int>, less<int>> minHeap;
29 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/5016258.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值