Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

155. Min Stack

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
2
3
4
5
6
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

這篇要實作一個有取得最小值功能的Stack,也是我們第一次真正用到class,class有幾個methods需要實作,python中很直覺想到用list,那最小值就是min(list),注意新增刪除元素都要更新最小值,取得最小時才不會出錯喔。

1
2
3
4
push()/pop(): FILO.
top(): Get first value.
getMin(): The smallest value in stack.
getStack(): Get stack.

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels