image.png

思路

image.png
image.png
image.png
image.png

code

  1. import java.util.PriorityQueue;
  2. class MedianFinder {
  3. private int count;
  4. private PriorityQueue<Integer> maxheap;
  5. private PriorityQueue<Integer> minheap;
  6. /** initialize your data structure here. */
  7. public MedianFinder() {
  8. count = 0;
  9. maxheap = new PriorityQueue<>((x,y)->y-x);//使用lambda来声明一个大根堆
  10. minheap = new PriorityQueue<>();
  11. }
  12. public void addNum(int num) {
  13. count++;
  14. maxheap.offer(num); //数据先流入左半部分的大根堆
  15. minheap.add(maxheap.poll()); //大根堆顶部流入右半部分的小根堆
  16. if((count&1)!=0) //如果是偶数 将右半部分的最小元素流入左根堆
  17. maxheap.add(minheap.poll());
  18. }
  19. public double findMedian() {
  20. if(count&1==0)
  21. return (double)maxheap.peek()+minheap.peek()/2;
  22. else
  23. return (double)maxheap.peek();
  24. }
  25. }