データストリームのLeetCode295中央値

  • 分析

      大きな根の杭と小さな根の杭の2つの杭を維持します。2つの状態を維持します。大きな根の杭の上部要素の値は、小さな根の杭の上部の要素の値よりも小さく、大きな根の杭と小さな根の杭の数の差は、 1、中央値または2つの杭の上部になるように1つの杭の平均値または上部要素。これは、2つのヒープ内の要素の数に関連しています。要素を挿入するときは、2つのヒープ状態を維持する方法のコードを参照してください。この質問は、ヒープ内の典型的な質問です。

  • コード
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();
 */

 

おすすめ

転載: blog.csdn.net/xiaoan08133192/article/details/109170328