思路
- 空间换时间,辅助栈,存储最小值
主------辅助
5 ------ 2
2 ------ 2
4 ------ 3
4 ------ 3
3 ------ 3
9 ------ 9
代码
import java.util.Stack;
public class Solution {
Stack<Integer> stack=new Stack<>();
Stack<Integer> help=new Stack<>();
public void push(int node) {
if(help.isEmpty()){ //help判断是否空
help.push(node);
}else{
help.push(Math.min(node,help.peek()));
}
stack.push(node);
}
public void pop() {
stack.pop();
help.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return help.peek();
}
} 
京公网安备 11010502036488号