295.Find Median from Data Stream

Question

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.
Example:

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

Thinking:

  • Method 1:
    • 通过堆结构来实现,堆结构是通过优先级队列实现的。
    • 维护一个递增堆和一个递减堆。
    • 通过判断两个堆的size判断总数是奇数还是偶数。
class MedianFinder {
    private List<Integer> list;
    /** initialize your data structure here. */
    public MedianFinder() {
        this.list = new ArrayList<>();
    }

    public void addNum(int num) {
        list.add(num);
    }

    public double findMedian() {
        int size = list.size();
        if(size % 2 != 0)
            return (double)list.get(size / 2);
        else{
            return (double)(list.get(size / 2) + list.get(size / 2 - 1)) / 2;
        }
    }
}

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

Second time

  1. Use two priority queue to solve this quesiton. Imgur
    class MedianFinder {
     /** initialize your data structure here. */
     PriorityQueue<Integer> min;
     PriorityQueue<Integer> max;
     public MedianFinder() {
         min = new PriorityQueue<>();
         max = new PriorityQueue<>(new Comparator<Integer>(){
             @Override
             public int compare(Integer n1, Integer n2){
                 return n2 - n1;
             }
         });
     }
     public void addNum(int num) {
         max.offer(num);
         min.offer(max.poll());
         if(max.size() < min.size()) max.offer(min.poll());
     }
     public double findMedian() {
         if(max.size() > min.size()) return (double)max.peek();
         else return (double)(max.peek() + min.peek()) / 2;
     }
    }
    /**
     * Your MedianFinder object will be instantiated and called as such:
     * MedianFinder obj = new MedianFinder();
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */