zoukankan      html  css  js  c++  java
  • [LeetCode]Find Median from Data Stream

    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:

    add(1)
    add(2)
    findMedian() -> 1.5
    add(3) 
    findMedian() -> 2







    class MedianFinder {
    public:
    
        // Adds a number into the data structure.
        void addNum(int num) {
            maxH.push(num);
            int t = maxH.top();
            maxH.pop(); minH.push(t);
            int m = maxH.size(), n = minH.size();
            if (n > m) {
                int t = minH.top();
                minH.pop(); maxH.push(t);
            }
        }
    
        // Returns the median of current data stream
        double findMedian() { 
            int m = maxH.size(), n = minH.size();
            if (!m && !n) return 0.0;
            if (m == n) return (maxH.top() + minH.top()) / 2.0;
            return (m > n) ? maxH.top() : minH.top();
        }
    private:
        priority_queue<int, vector<int>, less<int>> maxH;       // stores the smaller half
        priority_queue<int, vector<int>, greater<int>> minH;    // stores the larger half
    };
    
    // Your MedianFinder object will be instantiated and called as such:
    // MedianFinder mf;
    // mf.addNum(1); 
    // mf.findMedian();

    一个最小堆,一个最大堆,利用了堆的性质。
    只需要求中位数。

  • 相关阅读:
    codevs 3971 航班
    2015山东信息学夏令营 Day4T3 生产
    2015山东信息学夏令营 Day5T3 路径
    Tyvj 1221 微子危机——战略
    清北学堂模拟赛 求和
    NOIP2012同余方程
    NOIP2009 Hankson的趣味题
    bzoj1441 MIN
    国家集训队论文分类
    贪心 + DFS
  • 原文地址:https://www.cnblogs.com/shenbingyu/p/4908699.html
Copyright © 2011-2022 走看看