1、题目
题目解析:找到当前栈中元素的最小值
2、解法
import java.util.Stack;
public class Solution {
Stack<Integer> stk = new Stack<Integer>();
Stack<Integer> minStk = new Stack<Integer>();
public void push(int node) {
stk.push(node);
// 第一次添加的时候
if (minStk.empty()) {
minStk.push(node);
} else {
if (node >= minStk.peek()) {
minStk.push(minStk.peek());
} else {
minStk.push(node);
}
}
}
public void pop() {
stk.pop();
minStk.pop();
}
public int min() {
return minStk.peek();
}
public int top() {
return stk.peek();
}
}
时间复杂度位O(1)
3、思路
- 在一个栈的情况没法找到min值,因为没有办法进行排序
- 引入辅助栈的做法,但是空间复杂度位O(n)