155. Min Stack
Question:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Example:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
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
Source code:
Version 1
Idea:
Retrieving the minimum element is a key point, only one Stack can't handle this, because Stack are a type of container adpators with Last In First Out(LIFO).
So, we need to declare two Stack variables.
In the push() function, st
can be added directly. Howerver, min_st
must be checked whether the size of min_st
is empty or a top of value of min_st
is bigger than input value. If the IF statement is true, added input value to min_st
.
In the pop() function, we can't pop any value in min_st
. We should check a value of st.pop()
whether it's equal to min_st.pop()
.
Finally, we can get the minimum element by using getMin() function.
1 | class MinStack { |