150强访谈简单

最小堆栈

“最小堆栈”问题的详细指南和 Python 实现。

问题陈述

简单

设计一个支持压入、弹出、置顶以及在恒定时间内检索最小元素的堆栈。

实现 MinStack 类:

- MinStack() 初始化堆栈对象。

- push(val: int) 将元素 val 压入堆栈。

- pop() 删除堆栈顶部的元素。

- top() -> int 获取堆栈顶部的元素。

- getMin() -> int 检索堆栈中的最小元素。

您必须为每个函数实现一个时间复杂度为 O(1) 的解决方案。

约束条件
  • -2^31 <= val <= 2^31 - 1
  • Methods pop, top, and getMin are always called on non-empty stacks
  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin

示例

Example 1
Input
["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"]
[[], [-2], [0], [-3], [], [], [], []]
Output
[None, None, None, None, -3, None, 0, -2]
Explanation

MinStack created. Push -2, 0, -3. getMin() returns -3. Pop removes -3. top() returns 0. getMin() returns -2.

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 资源

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