Leetcode (295) 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.

  • 题意:给一个数据流,流中只会添加数字,不会删除,然后需要能够动态地查询流中的中位数。
  • 思路:因为流中只会添加数字不会删除,因此可以使用大顶堆小顶堆来维护这一个队列(大顶堆,即堆顶数字为堆中最大的,小顶堆,即堆顶数字为堆中最小的),并规定,小顶堆中的任意一个数字都比大顶堆的大,维护过程如下:
    1. 若小顶堆的size <= 大顶堆的size,则
      1. 若小顶堆为空,则直接插入
      2. 若将要插入的数字 >= 大顶堆堆顶,则插入小顶堆
      3. 若将要插入的数字 < 大顶堆堆顶,那么取出大顶堆堆顶放入小顶堆,插入的数字放入大顶堆
    2. 若小顶堆的size > 大顶堆的size,则
      1. 若要插入的数字 <= 小顶堆堆顶,则直接插入大顶堆
      2. 若插入的数字 > 小顶堆堆顶,则取出小顶堆堆顶放入大顶堆,插入的数字放入大顶堆
  • 查询过程如下:
    • 若小顶堆size+大顶堆size为奇数,则直接小顶堆堆顶即为中位数
    • 否则,(小顶堆堆顶+大顶堆堆顶) / 2 即为中位数
  • 当然,实现方面,若是只有添加,那么直接用priority_queue即可,若是有删除,则只能自己实现一个堆,然后在堆中删除,再维护一遍堆,同时保证小顶堆与大顶堆size之差最大为1,小顶堆的所有数字均大于等于大顶堆的所有数字即可。
class MedianFinder {
private:
    priority_queue<int,vector<int>,greater<int>> small_heap;
    priority_queue<int,vector<int>,less<int>>    big_heap;
public:

    // Adds a number into the data structure.
    void addNum(int num) {
        int small_size=small_heap.size(),big_size=big_heap.size();
        if(small_size>big_size){
            int stop=small_heap.top();
            if(stop>num){
                big_heap.push(num);
            }
            else{
                small_heap.pop();
                small_heap.push(num);
                big_heap.push(stop);
            }
        }
        else{
            if(!small_heap.empty()){
                int btop=big_heap.top();
                if(btop>num){
                    big_heap.pop();
                    big_heap.push(num);
                    small_heap.push(btop);
                }
                else{
                    small_heap.push(num);
                }
            }
            else{
                small_heap.push(num);
            }
        }
    }

    // Returns the median of current data stream
    double findMedian() {
        if(small_heap.empty()) return 0;
        else{
            int small_size=small_heap.size(),big_size=big_heap.size();
            if(small_size==big_size){
                return (small_heap.top()+big_heap.top())*0.5;
            }
            else{
                return small_heap.top();
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值