Question:
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.
Examples:[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.
For example:
addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2
思路:
利用两个堆,一个最大堆保存前一半数,堆顶元素是前一半最大值,另一个最小堆保存后一半数,堆顶元素是后一半最小值。保证两个堆大小只差1个元素或者相等。先把数据放入最大堆,再将其堆顶元素放入最小堆。如果最小堆元素个数比最大堆大,则把堆顶插入最大堆。
当两个堆大小相同,中位数为两个堆的堆顶元素之和。否则返回最大堆堆顶元素。
class MedianFinder {
/** initialize your data structure here. */
public MedianFinder() {
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer> (Collections.reverseOrder());
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer> ();
public void addNum(int num) {
maxHeap.add(num);
minHeap.add(maxHeap.poll());
if(minHeap.size() > maxHeap.size())
{
maxHeap.add(minHeap.poll());
}
}
public double findMedian() {
if(minHeap.size() == maxHeap.size())
{
return (minHeap.peek() + maxHeap.peek()) / 2.0;
}
return maxHeap.peek();
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
参考:https://segmentfault.com/a/1190000004194041
博主学习笔记,转载请注明出处,若有错误望指正,谢谢~^-^