zoukankan      html  css  js  c++  java
  • 数据流中的中位数

    题目描述

    如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。

    代码

    class Solution {
        vector<int> maxHeap, minHeap;
        int cnt = 0;
    public:
        void Insert(int num)
        {//在操作中,要保证最小堆的最小值要大于等于最大堆的最大值,且最大堆的个数要不少于最小堆的个数,最多多1
            ++cnt;
    
            if (maxHeap.empty()) {
                maxHeap.push_back(num);
                return;
            }
    
            if (minHeap.empty()) {
                if (num > maxHeap[0]) {
                    minHeap.push_back(num);
                } else {
                    minHeap.push_back(maxHeap[0]);
                    maxHeap[0] = num;
                }
                return;
            }
    
            if (cnt & 1) {//奇数个
                if (num > minHeap.front()) {
                    int t = minHeap.front();
                    pop_heap(minHeap.begin(), minHeap.end(), greater<int>());
                    minHeap.pop_back();
                    minHeap.push_back(num);
                    push_heap(minHeap.begin(), minHeap.end(), greater<int>());
    
                    maxHeap.push_back(t);
                    push_heap(maxHeap.begin(), maxHeap.end());
                } else {
                    maxHeap.push_back(num);
                    push_heap(maxHeap.begin(), maxHeap.end());
                }
            } else { //偶数个
                if (num >= maxHeap.front()) {
                    minHeap.push_back(num);
                    push_heap(minHeap.begin(), minHeap.end(), greater<int>());
                } else {
                    int t = maxHeap.front();
                    pop_heap(maxHeap.begin(), maxHeap.end());
                    maxHeap.pop_back();
    
                    maxHeap.push_back(num);
                    push_heap(maxHeap.begin(), maxHeap.end());
    
                    minHeap.push_back(t);
                    push_heap(minHeap.begin(), minHeap.end(), greater<int>());
                }
            }
        }
    
    
        double GetMedian()
        {
            if (cnt == 0) {
                return 0;
            }
            double  ans = 1.0 * maxHeap.front();
            if ((cnt & 1) == 0) {
                ans = (ans + minHeap.front()) / 2;
            }
            return ans;
        }
    };
    
  • 相关阅读:
    CentOS系统下NFS服务器
    网络封包分析
    Android端抓包方法
    SQL Server 2008从基础开始学习的历程(1)------创建表与查询
    序--CentOS6.5 mini 安装和基本配置
    MonkeyRunner(猴哥快跑)常用类方法总结
    python 开源数据抓取框架scrapy
    pycharm最新版注册
    python flask下传数据到js
    centos打架django + mysql环境
  • 原文地址:https://www.cnblogs.com/jecyhw/p/6655939.html
Copyright © 2011-2022 走看看