295. Find Median from Data Stream 剑指offer 数据流中的中位数

来源:互联网 发布:儿童医院在线咨询网络 编辑:程序博客网 时间:2024/05/19 19:42

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

Examples: 

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

For example:

addNum(1)addNum(2)findMedian() -> 1.5addNum(3) findMedian() -> 2.
class MedianFinder {public:    /** initialize your data structure here. */    MedianFinder() {            }        void addNum(int num) {        if(size&1)//奇数个        {            if(!minHeap.empty()&&num>minHeap.top())            {                minHeap.push(num);                num=minHeap.top();                minHeap.pop();            }            maxHeap.push(num);        }        else         {            if(!maxHeap.empty()&&num<maxHeap.top())            {                maxHeap.push(num);                num=maxHeap.top();                maxHeap.pop();            }            minHeap.push(num);        }        size++;    }        double findMedian() {        if(size&1) return minHeap.top();        else return static_cast<double>(minHeap.top()+maxHeap.top())/2.0;    }    private:    priority_queue<int,vector<int>,greater<int>> minHeap;//最小堆    priority_queue<int> maxHeap;//最大堆    int size=0;};/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */


阅读全文
0 0
原创粉丝点击