150 najlepszych wywiadówŁatwe

Minimalny stos

Szczegółowy przewodnik i implementacja Python dla problemu „Min Stack”.

Oświadczenie o problemie

Łatwe

Zaprojektuj stos obsługujący push, pop, top i pobieranie minimalnego elementu w stałym czasie.

Zaimplementuj klasę MinStack:

- MinStack() inicjuje obiekt stosu.

- push(val: int) umieszcza element val na stosie.

- pop() usuwa element na górze stosu.

- top() -> int pobiera górny element stosu.

- getMin() -> int pobiera minimalny element na stosie.

Dla każdej funkcji należy zaimplementować rozwiązanie o złożoności czasowej O(1).

Ograniczenia
  • -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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla stosu, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

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

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.