Stack

Stack 的運用

逆序:後進先出 (Last In First Out)

Depth-First Search

Eval語法分析 Parsing

括號 Parentheses

前後元素的配對

在 Python 中實作 Stack

使用 list
append() 跟 pop() 的 time complexity 都是 O(1)

Template

stack = [...]
while stack:
  cur = stack.pop()
  // ...
  stack.append(...)

Monotonic Stack

Monotonic Increasing/Decreasing Stack

list: [e0, e1, e2, …, etop] ⮂ in/out, If i < j ⇒ ei < ej

1. 循序尋找下一個比自己大/小的元素

2. 循序尋找最大/小值

  • 42
  • 739
  • 901

3. 找出第 i 個山峰或是山谷 (運用 2.)

  • 84
  • 1793

其他 Monotonic Stack 例題

  • 316
  • 907
  • 1944
  • 2866

相關例題

Last Updated on 2024/12/22 by A1go

目錄
Bitnami