建立大顶堆和小顶堆
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());
}
}