Python数据流中的中位数

本文阅读 2 分钟
首页 Python笔记 正文

构建一个最大堆和一个最小堆,分别存储比中位数小的数和大的数。当目前两堆总数为偶数的时候,把数字存入最大堆,然后重排最大堆,如果最大堆的堆顶数字大于最小堆堆顶数字,则把两个堆顶数字交换,重排两堆,此时两堆数字总数为奇数,直接输出最大堆堆顶数字即为中位数;如果当前两堆总数为技术的时候,把数字存入最小堆,重排最小堆,如果最大堆的堆顶数字大于最小堆堆顶数字,则把两个堆顶数字交换,重排两堆,此时两堆数字总数为偶数,取两堆堆顶数字做平均即为中位数。

  1. '''
  2. 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。
  3. 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。
  4. '''
  5. # -*- coding:utf-8 -*-
  6. class Solution:
  7. def __init__(self):
  8. self.left = []
  9. self.right = []
  10. self.count = 0
  11. def Insert(self, num):
  12. if self.count & 1 == 0:
  13. self.left.append(num)
  14. else:
  15. self.right.append(num)
  16. self.count += 1
  17. def GetMedian(self, x):
  18. if self.count == 1:
  19. return self.left[0]
  20. self.MaxHeap(self.left)
  21. self.MinHeap(self.right)
  22. if self.left[0] > self.right[0]:
  23. self.left[0], self.right[0] = self.right[0], self.left[0]
  24. self.MaxHeap(self.left)
  25. self.MinHeap(self.right)
  26. if self.count & 1 == 0:
  27. return (self.left[0] + self.right[0])/2.0
  28. else:
  29. return self.left[0]
  30. def MaxHeap(self, alist):
  31. length = len(alist)
  32. if alist == None or length <= 0:
  33. return
  34. if length == 1:
  35. return alist
  36. for i in range(length//2-1, -1, -1):
  37. k = i; temp = alist[k]; heap = False
  38. while not heap and 2*k < length-1:
  39. index = 2*k+1
  40. if index < length - 1:
  41. if alist[index] < alist[index + 1]: index += 1
  42. if temp >= alist[index]: heap = True
  43. else:
  44. alist[k] = alist[index]
  45. k = index
  46. alist[k] = temp
  47. def MinHeap(self, alist):
  48. length = len(alist)
  49. if alist == None or length <= 0:
  50. return
  51. if length == 1:
  52. return alist
  53. for i in range(length//2-1, -1, -1):
  54. k = i; temp = alist[k]; heap = False
  55. while not heap and 2 * k < length - 1:
  56. index = 2 * k+1
  57. if index < length - 1:
  58. if alist[index] > alist[index + 1]: index += 1
  59. if temp <= alist[index]:
  60. heap = True
  61. else:
  62. alist[k] = alist[index]
  63. k = index
  64. alist[k] = temp
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python二叉搜索树的第k个结点
« 上一篇 01-21
Python滑动窗口的最大值
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18501 篇
  • 评论总数:
    53360 条
  • 标签总数:
    8881 个
  • 总浏览量:
    23378149 次
  • 最后更新:
    4月27日

最多点赞

随便看看

标签TAG