• 当大根堆和小根堆的size都是0时,元素默认进大根堆
    • 1)num <= 大根堆的顶, num进大根堆,否则进小根堆
    • 2)大根堆的size比小根堆大2,大根堆堆顶进小根堆
      • 小根堆的size比大根堆大2, 小根堆堆顶进大根堆

    大根堆的堆顶和小根堆的堆顶就是中间的两个数

    例子 5 3 6 4 2 1
    image.png image.png
    image.png image.png
    image.png image.png
    image.png image.png
    image.png

    1. class MedianFinder {
    2. private PriorityQueue<Integer> maxh;
    3. private PriorityQueue<Integer> minh;
    4. public MedianFinder() {
    5. maxh = new PriorityQueue<>((o1, o2) -> o2 - o1);
    6. minh = new PriorityQueue<>((o1, o2) -> o1 - o2);
    7. }
    8. public void addNum(int num) {
    9. if (maxh.isEmpty()) {
    10. maxh.add(num);
    11. } else {
    12. if (maxh.peek() >= num) {
    13. maxh.add(num);
    14. } else {
    15. minh.add(num);
    16. }
    17. }
    18. balance();
    19. }
    20. public double findMedian() {
    21. if (maxh.size() == minh.size()) {
    22. return (double) (maxh.peek() + minh.peek()) / 2;
    23. } else {
    24. return maxh.size() > minh.size() ? maxh.peek() : minh.peek();
    25. }
    26. }
    27. private void balance() {
    28. if (maxh.size() == minh.size() + 2) {
    29. minh.add(maxh.poll());
    30. }
    31. if (maxh.size() == minh.size() - 2) {
    32. maxh.add(minh.poll());
    33. }
    34. }
    35. }