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:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
思路:
1、记录最小值、并且每次最小值一旦发生变更、便将次小值先压入栈、然后再压入最小值
2、这样子pop的时候发现一旦pop出来的是当前的最小值、便再pop一次、这样子就可以更新到次小值、确保之后的是最小值