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

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。