295. Find Median from Data Stream[Hard]

295. Find Median from Data Stream

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

For example, for arr = [2,3,4], the median is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

Constraints:

  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 104 calls will be made to addNum and findMedian.

Example

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

思路

  • PriorityQueue默认是小顶堆
  • 利用大小顶堆特性

整体偏大的小顶堆 4->5->6
整体偏小的大顶堆 3->2->1
小顶堆peek出4
大顶堆peek出3
得出结果3.5

题解

class MedianFinder {

        public MedianFinder() {
        }
	// 整体偏大的小顶堆
        Queue<Integer> largeMinHeap = new PriorityQueue<>();
	// 整体偏小的大顶堆
	// Queue<Integer> smallMaxHeap = new PriorityQueue<>(Comparator.reverseOrder());
        Queue<Integer> smallMaxHeap = new PriorityQueue<>((o1,o2)->o2.compareTo(o1));

        public void addNum(int num) {
            if (!smallMaxHeap.isEmpty() && smallMaxHeap.peek() < num)
                largeMinHeap.add(num);
            else
                smallMaxHeap.add(num);

            if (smallMaxHeap.size() > (largeMinHeap.size() + 1))
                largeMinHeap.add(smallMaxHeap.remove());
            if (largeMinHeap.size() > (smallMaxHeap.size() + 1))
                smallMaxHeap.add(largeMinHeap.remove());
        }

        public double findMedian() {
            if (smallMaxHeap.size() == largeMinHeap.size())
                return (smallMaxHeap.peek() + largeMinHeap.peek()) / 2.0;
            if (smallMaxHeap.size() > largeMinHeap.size())
                return smallMaxHeap.peek();
            return largeMinHeap.peek();
        }
}
posted @ 2023-02-17 17:15  AaronTanooo  阅读(23)  评论(0)    收藏  举报