数据流中的中位数

2020-07-24  本文已影响0人  Crazy_Bear
import java.util.*;
public class Solution {
    private PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(15, (a, b) -> b-a);
    int count = 0;
    public void Insert(Integer num) {
        if(count % 2 == 0) {
            maxHeap.offer(num);
            int max = maxHeap.poll();
            minHeap.offer(max);
        } else {
            minHeap.offer(num);
            int min = minHeap.poll();
            maxHeap.offer(min);       
        }
        count++;
    }

    public Double GetMedian() {
        if(count %2 == 1) return Double.valueOf(minHeap.peek());
        else return Double.valueOf((minHeap.peek() + maxHeap.peek()))/2;
    }
}
上一篇下一篇

猜你喜欢

热点阅读