150强访谈

从数据流中查找中值

“从数据流中查找中值”问题的详细指南和 Python 实现。

问题陈述

中位数是有序整数列表中的中间值。如果列表的大小是偶数,则没有中间值,中位数是中间两个值的平均值。

实现 MedianFinder 类:

- MedianFinder() 初始化 MedianFinder 对象。

- addNum(num: int) 将数据流中的整数 num 添加到数据结构中。

- findMedian() -> float 返回到目前为止所有元素的中位数。

输入是操作和参数的列表。实现一个返回结果列表的函数 medianFinder(operations: list, arguments: list) -> list (构造函数/addNum 为 None,findMedian 为 float)。

约束条件
  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian
  • At most 5 * 10^4 calls will be made to addNum and findMedian

示例

Example 1
Input
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
Output
[None, None, None, 1.5, None, 2.0]
Explanation

Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.

Need a Hint?
考虑使用堆/优先级队列特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。