题意: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
思路:这题正好在《剑指Offer》上见过,是用最大堆和最小堆来分别保存数据流的左半部分和右半部分,这样可以根据数据流长度的奇偶性来直接用最大堆最大值或者最大堆最大值和最小堆最小值的一半求得中位数。具体方法是,数据流中,奇数位数和偶数位数分别放入最小堆和最大堆,但是如何保证最大堆的最大值小于最小堆的最小值呢?只要当待加入最大堆的数大于最小堆的最小数,则把最大堆的最大数加入最小堆中,再把待加入数加入最大堆中。另一类反之,具体看代码:
class MedianFinder(object):
import heapq
def __init__(self):
"""
initialize your data structure here.
"""
self.heaps,self.heapb = [],[]
self.cnt = 0
def addNum(self, num):
"""
:type num: int
:rtype: void
"""
if self.cnt%2 == 0:
if self.heaps and self.heaps[0] < num:
heapq.heappush(self.heapb,-heapq.heappop(self.heaps))
heapq.heappush(self.heaps,num)
else:
heapq.heappush(self.heapb,-num)
else:
if self.heapb and -self.heapb[0] > num:
heapq.heappush(self.heaps,-heapq.heappop(self.heapb))
heapq.heappush(self.heapb,-num)
else:
heapq.heappush(self.heaps,num)
self.cnt += 1
def findMedian(self):
"""
:rtype: float
"""
# print self.heapb,self.heaps
if self.cnt:
if self.cnt%2!=0:
return -self.heapb[0]
else:
return (-self.heapb[0]+self.heaps[0])/2.0