美文网首页
剑指offer 数据流中的中位数

剑指offer 数据流中的中位数

作者: liust15 | 来源:发表于2019-04-16 09:47 被阅读0次

建立大顶堆和小顶堆

import java.util.PriorityQueue;

class Solution {
    PriorityQueue<Integer> maxHeap;
    PriorityQueue<Integer> minHeap;

    public Solution() {
        this.maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
        this.minHeap = new PriorityQueue<>();
    }

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

    }

    public Double GetMedian() {
        return maxHeap.size() == minHeap.size() ?
                (double) (maxHeap.peek() + minHeap.peek()) * 0.5
                : Double.valueOf(maxHeap.peek());
    }

}

相关文章

网友评论

      本文标题:剑指offer 数据流中的中位数

      本文链接:https://www.haomeiwen.com/subject/emjvwqtx.html