🌗 155. 最小栈
2022年10月10日
- algorithm
🌗 155. 最小栈
难度: 🌗
问题描述
解法
class MinStack {
// 思路:
// 2 个栈,一个栈进行常规操作,另一个栈存放非严格单调递减数
LinkedList<Integer> stack;
LinkedList<Integer> minS;
public MinStack() {
this.stack = new LinkedList<>();
this.minS = new LinkedList<>();
}
public void push(int val) {
stack.push(val);
if(minS.isEmpty() || val <= minS.peek()) {
minS.push(val);
}
}
public void pop() {
int val = stack.pop();
if(!minS.isEmpty() && val == minS.peek()) {
minS.pop();
}
}
public int top() {
if(stack.isEmpty()) {
return -1;
} else {
return stack.peek();
}
}
public int getMin() {
if(minS.isEmpty()) {
return -1;
} else {
return minS.peek();
}
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/