实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。
public class Solution {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public Solution() {
// do initialize if necessary
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
// write your code here
if(stack.isEmpty() || number < minStack.peek()){
stack.push(number);
minStack.push(number);
}else{
stack.push(number);
minStack.push(minStack.peek());
}
}
public int pop() {
// write your code here
minStack.pop();
return stack.pop();
}
public int min() {
// write your code here
return minStack.peek();
}
}