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.
classMedianFinder:def__init__(self):""" Initialize your data structure here. """self.small=[]# 数组的比较小的部分, 最小堆 (存储负数) small[0] 的正数其实是small中最大的self.large=[]# 数组的比较大的部分, 最小堆 (存储正数)defaddNum(self,num):""" Adds a num into the data structure. :type num: int :rtype: void """iflen(self.small)==len(self.large):heapq.heappush(self.large,-heapq.heappushpop(self.small,-num))else:heapq.heappush(self.small,-heapq.heappushpop(self.large,num))deffindMedian(self):""" Returns the median of current data stream :rtype: float """iflen(self.small)==len(self.large):returnfloat(self.large[0]-self.small[0])/2.0else:returnfloat(self.large[0])# Your MedianFinder object will be instantiated and called as such:# mf = MedianFinder()# mf.addNum(1)# mf.findMedian()