"Sword Finger Offer"-63, the median in the data stream

1. Knowledge points of this question

heap

2. Title description

How to get the median in a data stream? If an odd number of values ​​are read from the data stream, the median is the value in the middle after all the values ​​are sorted. If you read an even number of values ​​from the data stream, then the median is the average of the middle two numbers after all the values ​​are sorted. We use the Insert() method to read the data stream, and use the GetMedian() method to get the median of the currently read data.

3. Problem solving ideas

  1. Create a large top heap to store the smaller half of the input numbers, that is, the half to the left of the median
  2. Create a small top heap to store the larger half of the input numbers, that is, the half to the right of the median
  3. Ensure that the largest element in the big top heap <the smallest element in the small top heap, and the number of elements before them does not differ by more than 1
  4. Then the median can be obtained from the top elements of these two heaps

4. Code

public class Solution {
    
    
    // 总个数
    private int size = 0;
    // 小顶堆
    private PriorityQueue<Integer> left = new PriorityQueue<>((o1, o2) -> o2 -o1);
    // 大顶堆
    private PriorityQueue<Integer> right = new PriorityQueue<>();

    public void Insert(Integer num) {
    
    
        if (size % 2 == 0) {
    
    
            left.offer(num);
            right.offer(left.poll());
        } else {
    
    
            right.offer(num);
            left.offer(right.poll());
        }
        size++;
    }

    public Double GetMedian() {
    
    
        if (size % 2 == 0) {
    
    
            return (left.peek() + right.peek()) / 2.0;
        } else {
    
    
            return (double) right.peek();
        }
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/113850744