package class_07;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
*
* 一个数据流中,随时可以取得中位数
*
*/
public class Code_04_MadianQuick {
public static class MedianHolder {
private PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(new MaxHeapComparator());
private PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>(new MinHeapComparator());
private void modifyTwoHeapsSize() {
if (this.maxHeap.size() == this.minHeap.size() + 2) {
this.minHeap.add(this.maxHeap.poll());
}
if (this.minHeap.size() == this.maxHeap.size() + 2) {
this.maxHeap.add(this.minHeap.poll());
}
}
public void addNumber(int num) {
if (this.maxHeap.isEmpty()) {
this.maxHeap.add(num);
return;
}
if (this.maxHeap.peek() >= num) {
this.maxHeap.add(num);
} else {
if (this.minHeap.isEmpty()) {
this.minHeap.add(num);
return
实现一个数据流中,随时可以取得中位数
最新推荐文章于 2021-05-19 13:13:17 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)