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.

For example,
[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.

答案

class MedianFinder {
    /** initialize your data structure here. */
    PriorityQueue maxpq;
    PriorityQueue minpq;

    public MedianFinder() {
        minpq = new PriorityQueue();
        maxpq = new PriorityQueue(new Comparator() {
            public int compare(Integer a, Integer b) {
                if(a < b) return 1;
                else if(a == b) return 0;
                else return -1;
            }
        });
    }

    public void addNum(int num) {
        if(minpq.isEmpty()) {
            minpq.offer(num);
        }
        else if(maxpq.isEmpty()) {
            if(minpq.peek() < num) {
                maxpq.offer(minpq.poll());
                minpq.offer(num);
            }
            else
                maxpq.offer(num);
        }
        else {
            // Both heaps are not empty
            int maxnum_maxpq = maxpq.peek();
            int minnum_minpq = minpq.peek();
            int minheap_size = minpq.size();
            int maxheap_size = maxpq.size();

            if(num <= maxnum_maxpq) {
                if(maxheap_size <= minheap_size) maxpq.offer(num);
                else {
                    minpq.offer(maxpq.poll());
                    maxpq.offer(num);
                }
            }
            else if(num >= minnum_minpq) {
                if(minheap_size <= maxheap_size) minpq.offer(num);
                else {
                    maxpq.offer(minpq.poll());
                    minpq.offer(num);
                }
            }
            else {
                if(minheap_size <= maxheap_size) minpq.offer(num);
                else maxpq.offer(num);
            }
        }
    }

    public double findMedian() {
        int minheap_size = minpq.size();
        int maxheap_size = maxpq.size();
        if(maxheap_size > minheap_size) {
            return maxpq.peek();
        }
        else if(minheap_size > maxheap_size) {
            return minpq.peek();
        }
        else {
            double ret1 = (double)maxpq.peek();
            double ret2 = (double)minpq.peek();
            return (ret1 + ret2) / 2;
        }
    }

    
    
}

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

你可能感兴趣的:(Find Median From Data Stream)