两道题的思路是一样的,都是建立2个堆,一个是最小堆,一个是最大堆
295题
/*
* Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
* */
import java.util.Comparator;
import java.util.PriorityQueue;
//方法类似与480题的sliding window median
/*
Use two Heaps to store numbers. maxHeap for numbers smaller than current
* median, minHeap for numbers bigger than and equal to current median. A
* small trick I used is always make size of minHeap equal (when there are
* even numbers) or 1 element more (when there are odd numbers) than the
* size of maxHeap
*/
public class MedianFinder {
public static void main(String[] args) {
// TODO 自动生成的方法存根
MedianFinder mf = new MedianFinder();
mf.addNum(1);
mf.addNum(2);
System.out.println(mf.findMedian());
mf.addNum(3);
System.out.println(mf.findMedian());
}
PriorityQueue<Integer> minHeap;//使minHeap中的个数等于或者比maxHeap多1,这样对于返回中位数操作就相对简单
PriorityQueue<Integer> maxHeap;
public MedianFinder() {
this.minHeap = new PriorityQueue<>