0295. Find Median from Data Stream - kumaeki/LeetCode GitHub Wiki

0295. Find Median from Data Stream


The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

  • For example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

Constraints:

  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 10^4 calls will be made to addNum and findMedian.

Follow up:

  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

解法1

class MedianFinder {

    PriorityQueue<Integer> left;
    PriorityQueue<Integer> right;
    
    /** initialize your data structure here. */
    public MedianFinder() {
        // 倒序, 每次poll得到最大值
        left = new PriorityQueue<>((x,y)->(y-x));
        // 顺序, 每次poll得到最小值(默认)
        right = new PriorityQueue<>();
    }
    
    public void addNum(int num) {
        
        // 每次取出队列头部的值
        Integer l = left.poll();
        Integer r = right.poll();
        
        // 如果为空, 优先存入左边
        if(l == null)
            left.offer(num);
        
        // 如果只有一个数字, 那么按照大小决定如何存放
        else if(r == null){
            if(num < l){
                int temp = l;
                l = num;
                num = temp;
            }
            left.offer(l);
            right.offer(num);
        }
        
        // 如果有2个以上的数字
        else{
            
            // 先按照大小排序
            if(num > r){
                int temp = r;
                r = num;
                num = temp;
            }else if(num < l){
                int temp = l;
                l = num;
                num = temp;
            }
            
            // 最大值和最小值分别存入right和left
            left.offer(l);
            right.offer(r);
            
            // 然后按照队列的大小存放中间值(优先存入左边)
            if(right.size() < left.size())
                right.offer(num);
            else
                left.offer(num);
        }
        
    }
    
    public double findMedian() {
        // 如果两个队列长度相等, 各取头部的数字求平均值
        if(left.size() == right.size())
            return (left.peek() + right.peek()) / 2.0;
        // 如果长度不等, 那么去左边队列的头部数字
        else
            return left.peek() * 1.0;
    }
}

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