实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。
样例
如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1
public class MinStack {
Stack<Integer> main = new Stack();
Stack<Integer> help = new Stack();
public MinStack() {
// do intialization if necessary
}
/*
* @param number: An integer
* @return: nothing
*/
public void push(int number) {
// write your code here
main.push(number);
if (!help.isEmpty()) {
if (number <= help.peek()) {
help.push(number);
}
} else {
help.push(number);
}
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
int data = 0;
if (!main.isEmpty()) {
data = main.pop();
if (data == help.peek()) {
help.pop();
}
}
return data;
}
/*
* @return: An integer
*/
public int min() {
// write your code here
if (!help.isEmpty()) {
return help.peek();
} else {
return -1;
}
}
}