[LeetCode] 295. Find Median from Data Stream

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

For example,

[2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

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.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

找出数据流中的中位数。题意是给一个数据流,请根据题意设计几个函数。

其中需要实现的函数是addNum()和findMedian()。

思路是用两个堆做,一个是最大堆一个是最小堆。从一开始放入元素的时候就要始终保持两个堆的元素数量要一样,或者最大堆的元素多一个。如果放入了偶数个元素,那么最小堆和最大堆的顶端元素的平均值是中位数,如果放入了奇数个元素,则最大堆的顶端元素是中位数。下图例子应该能清楚说明问题(引用)。

时间O(logn) - pq的操作

空间O(n) - pq

Java实现,同时注意pq的写法,参见这个帖子

 1 class MedianFinder {
 2     private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
 3     private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
 4     private boolean even = true;
 5 
 6     /** initialize your data structure here. */
 7     public MedianFinder() {
 8 
 9     }
10 
11     public void addNum(int num) {
12         if (even) {
13             minHeap.offer(num);
14             maxHeap.offer(minHeap.poll());
15         } else {
16             maxHeap.offer(num);
17             minHeap.offer(maxHeap.poll());
18         }
19         even = !even;
20     }
21 
22     public double findMedian() {
23         if (even) {
24             return (maxHeap.peek() + minHeap.peek()) / 2.0;
25         } else {
26             return maxHeap.peek();
27         }
28     }
29 }
30 
31 /**
32  * Your MedianFinder object will be instantiated and called as such:
33  * MedianFinder obj = new MedianFinder(); obj.addNum(num); double param_2 =
34  * obj.findMedian();
35  */

相关题目

295. Find Median from Data Stream

480. Sliding Window Median

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12453585.html