LeetCode 295 median in data stream

  • analysis

      Maintain two piles, a large root pile and a small root pile. Maintain two states, the value of the top element of the large root pile is smaller than the value of the top element of the small root pile, and the difference between the number of the large root pile and the small root pile is not more than 1, so that the median or two pile tops The average value of, or the top element of one of the piles. This is related to the number of elements in the two heaps. When inserting an element, see the code for the method of maintaining two heap states. This question is a typical question in the heap! ! ! !

  • Code
class MedianFinder {
public:
    /** initialize your data structure here. */    
    priority_queue<int> big_heap;
    priority_queue<int, vector<int>, greater<int>> small_heap;

    MedianFinder() {                 
    }
    
    void addNum(int num) {
        int big_heap_size = big_heap.size();
        int small_heap_size = small_heap.size();

        if(big_heap_size == small_heap_size){//大根堆的个数和小根堆的个数相等的情况
            if(!big_heap.empty() && num > big_heap.top()){
                small_heap.push(num);
            }else{
                big_heap.push(num);
            }
        }else if(big_heap_size < small_heap_size){//大根堆的个数比小根堆少的情况
            if(!small_heap.empty() && num > small_heap.top()){
                big_heap.push(small_heap.top());
                small_heap.pop();
                small_heap.push(num);
            }else{
                big_heap.push(num);
            }
        }else{//大根堆的个数比小根堆duo的情况
            if(!big_heap.empty() && num < big_heap.top()){
                small_heap.push(big_heap.top());
                big_heap.pop();
                big_heap.push(num);
            }else{
                small_heap.push(num);
            }
        }
    }
    
    double findMedian() {
        int big_heap_size = big_heap.size();
        int small_heap_size = small_heap.size();
        double ans = 0;

        if(big_heap_size == small_heap_size){
            if(big_heap_size != 0){
                ans = (big_heap.top() + small_heap.top()) / 2.0;
            }
        }else if(big_heap_size > small_heap_size){
            ans = big_heap.top();
        }else{
            ans = small_heap.top();
        }
        return ans;
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

 

Guess you like

Origin blog.csdn.net/xiaoan08133192/article/details/109170328