题解 | #数据流中的中位数#
数据流中的中位数
http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1
import java.util.*;
public class Solution {
// 存放右边元素 如果是奇数时候 保证右边元素比左边元素多1 比如 12345 左边12 右边 345
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// 存放左边元素
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a,b)->b-a);
public void Insert(Integer num) {
if(minHeap.isEmpty() || num > minHeap.peek()) {
minHeap.add(num);
if (minHeap.size() - maxHeap.size() >= 2) {
maxHeap.add(minHeap.poll());
}
}else {
maxHeap.add(num);
if (maxHeap.si***Heap.size() >= 1) {
minHeap.add(maxHeap.poll());
}
}
}
public Double GetMedian() {
return minHeap.size() > maxHeap.size() ? (double)minHeap.peek() : (double)(minHeap.peek() + maxHeap.peek())/2;
}
}