数据流中的中位数

来源:互联网 发布:淘宝联盟官方发单助手 编辑:程序博客网 时间:2024/04/28 18:24
题目描述

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

IDEA

1.采用插入排序,插入一个,调整一次顺序;

2.两个堆实现。一个大顶堆,一个小顶堆,大顶堆中所有数<=小顶堆中所有数。

CODE

1.

class Solution {private:    vector<int> vec;    int n;public:    void Insert(int num)    {        vec.push_back(num);        n=vec.size();        int i=n-1;        while(i>0&&vec[i]<vec[i-1]){            int tmp=vec[i-1];            vec[i-1]=vec[i];            vec[i]=tmp;            i--;        }     }    double GetMedian()    {         return (vec[n/2]+vec[(n-1)/2])/2.0;    }};

2.

class Solution {private:    int count=0;    priority_queue<int,vector<int>,less<int> >big_heap;    priority_queue<int,vector<int>,greater<int> >small_heap;public:    void Insert(int num)    {        count++;        if(count%2){            small_heap.push(num);            big_heap.push(small_heap.top());            small_heap.pop();                    }else{            big_heap.push(num);            small_heap.push(big_heap.top());            big_heap.pop();        }    }    double GetMedian()    {         if(count%2){            return big_heap.top();        }else{            return (big_heap.top()+small_heap.top())/2.0;        }    }};




0 0