Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.
Example 1:
1 | Input |
Explanation
1 | MinStack minStack = new MinStack(); |
這篇要實作一個有取得最小值功能的Stack,也是我們第一次真正用到class,class有幾個methods需要實作,python中很直覺想到用list,那最小值就是min(list),注意新增刪除元素都要更新最小值,取得最小時才不會出錯喔。
1 | push()/pop(): FILO. |
如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)