Find median value from a growing set

后端 未结 8 1588
灰色年华
灰色年华 2020-12-04 10:03

I came across an interesting algorithm question in an interview. I gave my answer but not sure whether there is any better idea. So I welcome everyone to write something abo

8条回答
  •  执念已碎
    2020-12-04 10:45

    We can difine a min and max heap to store numbers. Additionally, we define a class DynamicArray for the number set, with two functions: Insert and Getmedian. Time to insert a new number is O(lgn), while time to get median is O(1).

    This solution is implemented in C++ as the following:

    template class DynamicArray
    {
    public:
        void Insert(T num)
        {
            if(((minHeap.size() + maxHeap.size()) & 1) == 0)
            {
                if(maxHeap.size() > 0 && num < maxHeap[0])
                {
                    maxHeap.push_back(num);
                    push_heap(maxHeap.begin(), maxHeap.end(), less());
    
                    num = maxHeap[0];
    
                    pop_heap(maxHeap.begin(), maxHeap.end(), less());
                    maxHeap.pop_back();
                }
    
                minHeap.push_back(num);
                push_heap(minHeap.begin(), minHeap.end(), greater());
            }
            else
            {
                if(minHeap.size() > 0 && minHeap[0] < num)
                {
                    minHeap.push_back(num);
                    push_heap(minHeap.begin(), minHeap.end(), greater());
    
                    num = minHeap[0];
    
                    pop_heap(minHeap.begin(), minHeap.end(), greater());
                    minHeap.pop_back();
                }
    
                maxHeap.push_back(num);
                push_heap(maxHeap.begin(), maxHeap.end(), less());
            }
        }
    
        int GetMedian()
        {
            int size = minHeap.size() + maxHeap.size();
            if(size == 0)
                throw exception("No numbers are available");
    
            T median = 0;
            if(size & 1 == 1)
                median = minHeap[0];
            else
                median = (minHeap[0] + maxHeap[0]) / 2;
    
            return median;
        }
    
    private:
        vector minHeap;
        vector maxHeap;
    };
    

    For more detailed analysis, please refer to my blog: http://codercareer.blogspot.com/2012/01/no-30-median-in-stream.html.

提交回复
热议问题