当前位置:网站首页>Force buckle 295 Median data flow

Force buckle 295 Median data flow

2022-06-22 02:49:00 SS_ zico

The median is the number in the middle of the sequential table . If the list length is even , The median is the average of the two middle numbers .

for example ,

[2,3,4] The median of is 3

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

Design a data structure that supports the following two operations :

void addNum(int num) - Add an integer from the data stream to the data structure .
double findMedian() - Returns the median of all current elements .
Example :

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

Method 1 : Insertion sort

class MedianFinder {
    
    vector<int> store; // resize-able container

public:
    // Adds a number into the data structure.
    void addNum(int num)
    {
    
        if (store.empty())
            store.push_back(num);
        else
            store.insert(lower_bound(store.begin(), store.end(), num), num);     // binary search and insertion combined
    }

    // Returns the median of current data stream
    double findMedian()
    {
    
        int n = store.size();
        return n & 1 ? store[n / 2] : (store[n / 2 - 1] + store[n / 2]) * 0.5;
    }
};

Time complexity :O(n)
Spatial complexity :O(n)

Method 2 : Two piles

class MedianFinder {
    
    priority_queue<int> lo;                              // max heap
    priority_queue<int, vector<int>, greater<int>> hi;   // min heap

public:
    // 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;
    }
};
/** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */

Time complexity :O(longn)
Spatial complexity :O(n)

原网站

版权声明
本文为[SS_ zico]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211652524606.html