题意:
实现求最小值 且 操作时间复杂度都是 O(1) 的栈
push(value):将value压入栈中
pop():弹出栈顶元素
top():获取栈顶元素
min():获取栈中最小元素
知识:
Stack<>s=new Stack<Integer>();
s.isEmpty();
s.push(node);
s.peek()
help.pop();
思路:
辅助栈记录入栈顺序中的不递增数字。
即栈顶维护当前最小值。
出栈数字是辅助栈顶数字时,辅助栈顶也需要出栈。
入栈时判断是否等于小于当前最小值
注意
栈为空是不能有peek() pop等操作
import java.util.Stack;
public class Solution {
Stack<>s=new Stack<Integer>();
Stack<Integer>help=new Stack<Integer>();
public void push(int node) {
if(help.isEmpty()||node<=help.peek()){
help.push(node);
}
s.push(node);
}
public void pop() {
if(s.peek()==help.peek()){
help.pop();
}
s.pop();
}
public int top() {
return s.peek();
}
public int min() {
return help.peek();
}
}