1 """ 2 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. 3 For example, 4 [2,3,4], the median is 3 5 [2,3], the median is (2 + 3) / 2 = 2.5 6 Design a data structure that supports the following two operations: 7 void addNum(int num) - Add a integer number from the data stream to the data structure. 8 double findMedian() - Return the median of all elements so far. 9 Example: 10 addNum(1) 11 addNum(2) 12 findMedian() -> 1.5 13 addNum(3) 14 findMedian() -> 2 15 """ 16 """ 17 用一个大顶堆和一个小顶堆来维护数据, 18 每次每个数进来,先把它丢进小顶堆,然后把小顶堆的堆顶丢进大顶堆, 19 调整两个堆,使得size 差最大为1。 20 这么搞的好处在于,小顶堆是数据流里前一半大的数,大顶堆是数据流里后一半的大的数, 21 而且小顶堆的size一定 >= 大顶堆的size, 22 小顶堆的堆顶M是小顶堆里最小的数,大顶堆的堆顶N是大顶堆里最大的数, 23 如果两个堆的size相同,那么中位数就是return (M + N) / 2.0 24 否则,return M / 1.0。 25 注意python没有大顶堆,所以放进大顶堆的数乘了-1, 取出来的时候也要记得 * -1 26 传送门:https://blog.csdn.net/qq_32424059/article/details/90346347 27 """ 28 29 from heapq import * 30 class MedianFinder: 31 32 def __init__(self): 33 """ 34 initialize your data structure here. 35 """ 36 self.max_h = list() 37 self.min_h = list() 38 heapify(self.max_h) 39 heapify(self.min_h) 40 41 def addNum(self, num: int) -> None: 42 heappush(self.min_h, num) 43 heappush(self.max_h, -heappop(self.min_h)) 44 if len(self.max_h) > len(self.min_h): 45 heappush(self.min_h, -heappop(self.max_h)) 46 47 def findMedian(self) -> float: 48 max_len = len(self.max_h) 49 min_len = len(self.min_h) 50 if max_len == min_len: # 有两个候选中位数 51 return (self.min_h[0] + -self.max_h[0]) / 2. 52 else: # 小顶堆的size 一定 >= 大顶堆的size,所以答案就是小顶堆的堆顶 53 return self.min_h[0] / 1.
原文地址:https://www.cnblogs.com/yawenw/p/12357439.html
时间: 2024-10-08 18:17:20