算法分析课每周练习 Find Median from Data Stream
来源:互联网 发布:java异步http请求post 编辑:程序博客网 时间:2024/06/14 03:06
题目
Find Median from Data Stream
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.
from heapq import *class MedianFinder: def __init__(self): self.small = [] # the smaller half of the list, max heap (invert min-heap) self.large = [] # the larger half of the list, min heap def addNum(self, num): if len(self.small) == len(self.large): heappush(self.large, -heappushpop(self.small, -num)) else: heappush(self.small, -heappushpop(self.large, num)) def findMedian(self): if len(self.small) == len(self.large): return float(self.large[0] - self.small[0]) / 2.0 else: return float(self.large[0])
本来以为是用平衡搜索树做的,看了答案原来是维持两个堆,实现起来确实简单多了
阅读全文
0 0
- 算法分析课每周练习 Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream
- Find Median from Data Stream leetcode 295
- LeetCode Find Median from Data Stream
- leetcode 295:Find Median from Data Stream
- [leetcode295]Find Median from Data Stream
- leetcode 295 : Find Median from Data Stream
- [LeetCode 295] Find Median from Data Stream
- Leetcode -- Find Median from Data Stream
- leetcode之Find Median from Data Stream
- [LeetCode] Find Median from Data Stream
- [leetcode][C++]Find Median from Data Stream
- 崩溃相关工具类
- php artisan make:auth 报错 not defined
- Django-内置分页
- Beautiful Soup
- 一个诡异的C++内存泄露问题。
- 算法分析课每周练习 Find Median from Data Stream
- linux学习之文件
- Android实现全屏和无标题栏的两种办法
- 关闭相关工具类
- 一个简单的远程登录脚本
- 数据去重的问题
- 算法学习(排序四)最大子数组问题
- 日期常用工具类
- springmvc+activemq1