class MinStack {
/**
* initialize your data structure here.
*/
//使用一个额外的辅助栈,
// push时,当x小于等于辅助栈的栈顶时,push辅助栈。
// pop时,当辅助栈的栈顶和当前栈相同时在一起POP。
//这样辅助栈的栈顶会一直保持最小。
Stack<Integer> min;
Stack<Integer> stack;
public MinStack() {
stack = new Stack<Integer>();
min = new Stack<Integer>();
}
public void push(int x) {
stack.push(x);
if (min.empty()) {
min.push(x);
} else {
if (x <= min.peek()) {
min.push(x);
}
}
}
public void pop() {
if (min.peek().equals(stack.peek())) {
min.pop();
}
if (!stack.empty()) {
stack.pop();
} else
throw new RuntimeException("11");
}
public int top() {
if (!stack.empty()) {
return stack.peek();
} else
throw new RuntimeException("11");
}
public int getMin() {
if (!min.empty()) {
return min.peek();
} else {
throw new RuntimeException("11");
}
}
}
最小栈
skyyemperor
·2020-04-18
·382 次阅读
Comments | 0 条评论