思路
不同步辅助栈,时间复杂度O(1),空间复杂度O(n)。
基数栈,在存放数据的栈里存放val-min,min作为基数单独用int变量存放。
基数栈时间复杂度O(1),空间复杂度O(1),致命缺陷是存放val-min导致可push数据的域值折半。
辅助栈代码
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> helper = new Stack<Integer>();
public void push(int node) {
stack.push(node);
if(helper.empty() || node <= helper.peek()) {
helper.push(node);
}
}
public void pop() {
if(!stack.empty()) {
if(stack.peek() == helper.peek()) {
helper.pop();
}
stack.pop();
}
}
public int top() {
if(!stack.empty()) {
return stack.peek();
}
throw new RuntimeException("栈空");
}
public int min() {
if(!stack.empty()) {
return helper.peek();
}
throw new RuntimeException("栈空");
}
}
基数栈代码
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<Integer>();
private int _min;
private int _top;
public void push(int node) {
_top = node;
if(stack.empty()) {
_min = node;
}
stack.push(node - _min);
if(node < _min) {
_min = node;
}
}
public void pop() {
if(!stack.empty()) {
if(stack.peek() < 0) {
// stack.pop() == _top - 上一个_min
// 所以_min = _top - stack.pop();
_min -= stack.peek();
}
stack.pop();
if(!stack.empty()) {
// 连续最小值情况的考虑
_top = _min + stack.peek() > 0 ? stack.peek() : 0;
}
}
}
public int top() {
if(!stack.empty()) {
return _top;
}
throw new RuntimeException("栈空");
}
public int min() {
if(!stack.empty()) {
return _min;
}
throw new RuntimeException("栈空");
}
}