• leetcode 295 数据流中中位数


    方法一

    1. class MedianFinder:
    2. def __init__(self):
    3. from sortedcontainers import SortedList
    4. self.right = 0
    5. self.arr = SortedList()
    6. def addNum(self, num: int) -> None:
    7. self.arr.add(num)
    8. self.right += 1
    9. def findMedian(self) -> float:
    10. if self.right % 2 == 0 :
    11. return self.arr[(self.right - 1) // 2] / 2 + self.arr[(self.right + 1) // 2] /2
    12. else :
    13. return self.arr[self.right // 2]

    方法二

    1. from heapq import *
    2. class MedianFinder(object):
    3. # 维护两个堆,一个大顶堆,一个小顶堆,小顶堆里的数比大顶堆里的数都要大,
    4. # 如果有两个潜在的中位数(两个堆size相同),数据流的中位数就是两个堆顶之和除以2
    5. # 如果只有一个中位数,就看size更小的那个堆的堆顶
    6. # 新进来的数都丢进小顶堆,然后把小顶堆的堆顶丢到大顶堆,
    7. # 调整两个堆,使得size 差最大为1
    8. def __init__(self):
    9. """
    10. initialize your data structure here.
    11. """
    12. self.max_h = list()
    13. self.min_h = list()
    14. heapify(self.max_h)
    15. heapify(self.min_h)
    16. def addNum(self, num):
    17. """
    18. :type num: int
    19. :rtype: None
    20. """
    21. heappush(self.min_h, num)
    22. heappush(self.max_h, -heappop(self.min_h))
    23. if len(self.max_h) > len(self.min_h):
    24. heappush(self.min_h, -heappop(self.max_h))
    25. def findMedian(self):
    26. """
    27. :rtype: float
    28. """
    29. max_len = len(self.max_h)
    30. min_len = len(self.min_h)
    31. if max_len == min_len: #有两个候选中位数
    32. return (self.min_h[0] + -self.max_h[0]) / 2.
    33. else:#小顶堆的size 一定 >= 大顶堆的size,所以答案就是小顶堆的堆顶
    34. return self.min_h[0] / 1.
    35. # Your MedianFinder object will be instantiated and called as such:
    36. # obj = MedianFinder()
    37. # obj.addNum(num)
    38. # param_2 = obj.findMedian()
  • 相关阅读:
    2024年软考重大改革
    Arnold置乱
    SpringBoot+Vue项目实现高校学生健康打卡系统
    qt化步骤
    【PHPWord】基于ThinkPHP6的Word模板处理和导出PDF文件的带源码 | 答读者问
    复盘Linux期末考试【已凉凉】
    新浪股票行情数据接口有什么作用?
    Webpack介绍大全
    “第五十二天”
    【学生管理系统】学生管理(重点)
  • 原文地址:https://blog.csdn.net/garrulousabyss/article/details/137937467