[leetcode] 295. Find Median from Data Stream

来源:互联网 发布:中国gdp数据 编辑:程序博客网 时间:2024/06/03 16:42
  • https://leetcode.com/problems/find-median-from-data-stream/solution/
class MedianFinder {    priority_queue<int> lo;                              // max heap    priority_queue<int, vector<int>, greater<int>> hi;   // min heappublic:    // Adds a number into the data structure.    void addNum(int num)    {        lo.push(num);                                    // Add to max heap        hi.push(lo.top());                               // balancing step        lo.pop();        if (lo.size() < hi.size()) {                     // maintain size property            lo.push(hi.top());            hi.pop();        }    }    // Returns the median of current data stream    double findMedian()    {        return lo.size() > hi.size() ? (double) lo.top() : (lo.top() + hi.top()) * 0.5;    }};
原创粉丝点击