Algorithm I 筆記撰寫計畫 第九天第二題,共兩題。
- 難度:
Easy - 花費時間: 10 min
- 題目: 232. Implement Queue using Stacks
使用最多兩個 Stacks 來建構一個 Queue
點我開啟限制與範例
限制:
1 <= x <= 9- At most
100calls will be made topush,pop,peek, andempty. - All the calls to
popandpeekare valid.
Example 1:
1 | Input |
筆記
使用兩個 stack 。
mainStack: 儲存所有資料。subStack: 當需要存取資料時,把mainStack的資料全部pop()到這,這樣最後一個 pop() 進來的資料,其實就是第一個被放進mainStack的資料,也就達到了題目要的效果。
1 | class MyQueue { |
下面也提供 TypeScript 的寫法。
1 | class MyQueue { |
成績
| Language | Runtime | Beats | Memory Usage | Beats |
|---|---|---|---|---|
| Java | 0 ms | 100% | 39.8 MB | 99.19% |
| TypeScript | 89 ms | 69.74% | 43.1 MB | 49.67% |
