Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Similar one as LintCode "Data Stream Median".

class MedianFinder {
    priority_queue<int> hl; // max-heap
    priority_queue<int, vector<int>, std::greater<int> > hr; // min-heap
public:

    // Adds a number into the data structure.
    void addNum(int num) {
        if(hl.empty())
        {
            hl.push(num);
        }
        else
        {
            if(num <= hl.top())
            {
                hl.push(num);
            }
            else
            {
                hr.push(num);
            }
            // main
            if(hl.size() > (hr.size() + 1))
            {
                hr.push(hl.top());
                hl.pop();
            }
            else if(hr.size() > hl.size())
            {
                hl.push(hr.top());
                hr.pop();
            }
        }
    }

    // Returns the median of current data stream
    double findMedian() 
    {
        if(hl.size() > hr.size())
        {
            return hl.top() * 1.;        
        }
        return (hl.top() + hr.top()) / 2.0;
    }
};
posted on 2015-10-20 14:05  Tonix  阅读(148)  评论(0编辑  收藏  举报