数据流中的中位数

题目描述

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

代码

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;
    }
};

posted on 2017-04-01 14:40  jec  阅读(176)  评论(0编辑  收藏  举报

导航