https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
题目要求访问每个函数的时间复杂度为O(1),因此不能实现遍历操作,这里引入了两个栈,另外一个栈用于存储最小值,非常妙👍
双栈法
public class MinStack {
Stack<Integer> s1 = new Stack<Integer>();//用于栈的push与pop
Stack<Integer> s2 = new Stack<Integer>();//用于存储最小min
public void push(int node) {
s1.push(node);
if (s2.isEmpty() || s2.peek() > node) {
s2.push(node);
} else {
s2.push(s2.peek());
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}