剑指Offer: 数据流中的中位数;C++容器适配器之priority_queue

来源:互联网 发布:游侠网软件下载 编辑:程序博客网 时间:2024/06/04 00:25

数据流中的中位数


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


维护一个最大堆,一个最小堆,两个堆大小差值小于等于1。
在这里使用的优先队列。


class Solution {public:    void Insert(int num)    {        if(big.empty()||num<=big.top()) big.push(num);        else    small.push(num);        while(big.size()>small.size()+1){            small.push(big.top());            big.pop();        }        while(small.size()>big.size()+1){            big.push(small.top());            small.pop();        }    }    double GetMedian()    {         if(big.size()==small.size()){            return (big.top()+small.top())/(double)2;        }        else if(big.size()<small.size()){            return small.top();        }        else{            return big.top();        }    }private:    priority_queue<int> big;//最大堆    priority_queue<int,vector<int>,greater<vector<int>::value_type>> small;//最小堆};

C++容器适配器之priority_queue


Reference:
http://www.cnblogs.com/mfryf/archive/2012/09/05/2671883.html


一、使用:priority_queue

priority_queue<int> qb;//默认最大堆priority_queue<int,vector<int>,greater<vector<int>::value_type>> qs;//最小堆

二、接口(对于队列):

1、pop()
2、top():只适用于priority_queue。
3、emplace()
4、push() size()
而:
front() back()只适用于queue。


注释掉的是不支持的。


#include <iostream>#include <queue>using namespace std;int main(){    priority_queue<int,vector<int>,greater<vector<int>::value_type>> q;//small    q.push(7);    q.push(2);    q.push(10);    q.push(4);    q.push(5);    cout<<"head\t"<<q.top()<<endl;//    cout<<"tail\t"<<q.back()<<endl;    cout<<"size\t"<<q.size()<<endl;    q.pop();//auto h=并没有返回值    cout<<"head\t"<<q.top()<<endl; //   cout<<"now head\t"<<q.front()<<endl;    q.emplace(6);//调用构造函数    cout<<"head\t"<<q.top()<<endl; //   cout<<"now tail\t"<<q.back()<<endl;    cout << "Hello world!\t\t\t@zem" << endl;    return 0;}

这里写图片描述

0 0
原创粉丝点击