题解 | #数据流中的中位数#

数据流中的中位数

https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

import java.util.*;

public class Solution {

    private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);

    public void Insert(Integer num) {
        minHeap.offer(num);
        maxHeap.offer(minHeap.poll());
        if (minHeap.size() < maxHeap.size()) {
            minHeap.offer(maxHeap.poll());
        }
    }

    public Double GetMedian() {
        if (minHeap.size() > maxHeap.size()) {
            return (double) minHeap.peek();
        }
        return (minHeap.peek() + maxHeap.peek()) / 2.0;
    }


}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务