求数据流中位数

初学见解
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class toGetMedian{
private:
    vector<int> maxheap;
    vector<int> minheap;
//当父节点的键值总是大于或等于任何一个子节点的键值时为最大堆。 大===小
//当父节点的键值总是小于或等于任何一个子节点的键值时为最小堆。 小---大
public:
    void Insert(int num)    //获取数据流
    {
       int size = maxheap.size() + minheap.size();//maxheap 最小堆, minheap 最大堆
       if(size&1){                                   //第偶数个的情况,下标从0开始,size实际为奇数
            int tmp = num;//25
            if((!maxheap.empty())&&(num < maxheap[0])){  //maxheap.empty()判断容器是否为空
                tmp = maxheap[0];  // 堆未建成,此处使用交换
                maxheap[0] = num;
                make_heap(maxheap.begin(),maxheap.end());//将[first, last)范围进行堆排序、生成大顶堆 /建堆
            }
       //最小堆为空,往最大堆中插入 /第二轮时 和 num > maxheap[0]---最大值
            minheap.push_back(tmp);将值tmp放入容器minheap中
            push_heap(minheap.begin(),minheap.end(),greater<int>());//生成小顶堆  /只有一个元素时,不能构成堆,也就无需先make_heap建堆
       }
       else{                                        //第奇数个的情况
            int tmp = num;//36
            if((!minheap.empty())&&(num > minheap[0])){  //minheap.empty()判断容器是否为空
                tmp = minheap[0]; // 堆未建成,此处使用交换
                minheap[0] = num;
                make_heap(minheap.begin(),minheap.end(),greater<int>());//生成小顶堆 /建堆
            }
     //最大堆为空,往最小堆中插入  /第一轮 和 num < minheap[0]--最小值
            maxheap.push_back(tmp);//将值tmp放入容器maxheap中
            push_heap(maxheap.begin(),maxheap.end());//生成大顶堆   /只有一个元素时,不能构成堆,也就无需先make_heap建堆
       }
    }

    double GetMedian()    //取得中位数
    {
        int size = maxheap.size() + minheap.size();//容器中数据个数
        double median;   //中位数
        if(size & 1){  //size为奇数
            median = maxheap[0];
        }
        else{      //size位偶数
            median =  (maxheap[0] + minheap[0])/2.;
        }

        return median;
    }
};

int main()
{
    toGetMedian test;
    test.Insert(1);
    test.Insert(7);
    test.Insert(3);
    test.Insert(8);
    test.Insert(17);
    test.Insert(62);
    test.Insert(2);

    cout << test.GetMedian() << endl;

    return 0;
}

大佬链接:https://blog.csdn.net/m0_37950361/article/details/80537646
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值