Description
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.
问题描述
设计stack,支持push,pop, top, 以及获取最小元素,并且这些操作在常量时间内完成
问题分析
基本思想是,当出栈元素为当前最小值时,当前最小值需要改变
步骤为,维护一个min,当元素小于min时,将min入栈,并且将min置为元素,将元素入栈。
出栈时,若出栈元素为min,则将min置为stack.pop()
解法
class MinStack {
int min = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<Integer>();
public void push(int x) {
if(x <= min){
stack.push(min);
min=x;
}
stack.push(x);
}
public void pop() {
//注意这里,出栈了两次
if(stack.pop() == min) min=stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}