题解 | #数据流中的中位数#

数据流中的中位数

https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

class Solution {
  public:
#define SCD static_cast<double>
    template<class T>
    struct greater {
        bool operator()(const T& x, const T& y) {
            return x > y;
        }
    };
    template<class T>
    struct less {
        bool operator()(const T& x, const T& y) {
            return x < y;
        }
    };

    priority_queue<int, vector<int>, less<int>> max;//小堆
    priority_queue<int, vector<int>, greater<int>> min;//大堆


    void Insert(int num) {
        min.push(num);
        max.push(min.top());
        min.pop();
        
        if (min.size()<max.size())
        {
            min.push(max.top());
            max.pop();
        }
       
    }
    double GetMedian()
    {
        if(min.size()>max.size())
            return (double)min.top();
        else
         {
            return (double)(min.top()+max.top())/2; 
         }

    }

};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务