文章目录
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
思路
参考:
https://leetcode-cn.com/problems/min-stack/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-38/
解法1-两个栈
(1)if(x <= stackMin.peek())
(2)合在一起写不能AC。
执行用时 :7 ms, 在所有 Java 提交中击败了88.72%的用户
内存消耗 :40.2 MB, 在所有 Java 提交中击败了66.08%的用户
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> stackMin;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
stackMin = new Stack<>();
}
public void push(int x) {
stack.push(x);
if(!stackMin.isEmpty()){
if(x <= stackMin.peek()){ //eror1
stackMin.push(x);
}
}else{
stackMin.push(x);
}
}
public void pop() {
int top = stack.pop();
int min = stackMin.peek();
if(top==min){
stackMin.pop();
}
// if( stack.pop() == stackMin.peek()){ error2
// stackMin.pop();
// }
}
public int top() {
return stack.peek();
}
public int getMin() {
return stackMin.peek();
}
}
解法2-一个栈+变量
https://leetcode.com/problems/min-stack/discuss/49014/Java-accepted-solution-using-one-stack
class MinStack {
int min = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<Integer>();
public void push(int x) {
//当前值更小
if(x <= min){
//将之前的最小值保存
stack.push(min);
//更新最小值
min=x;
}
stack.push(x);
}
public void pop() {
//如果弹出的值是最小值,那么将下一个元素更新为最小值
if(stack.pop() == min) {
min=stack.pop();
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
解法3-一个栈+差值
https://leetcode.com/problems/min-stack/discuss/49031/Share-my-Java-solution-with-ONLY-ONE-stack
public class MinStack {
long min;
Stack<Long> stack;
public MinStack(){
stack=new Stack<>();
}
public void push(int x) {
if (stack.isEmpty()) {
min = x;
stack.push(x - min);
} else {
stack.push(x - min);
if (x < min){
min = x; // 更新最小值
}
}
}
public void pop() {
if (stack.isEmpty())
return;
long pop = stack.pop();
//弹出的是负值,要更新 min
if (pop < 0) {
min = min - pop;
}
}
public int top() {
long top = stack.peek();
//负数的话,出栈的值保存在 min 中
if (top < 0) {
return (int) (min);
//出栈元素加上最小值即可
} else {
return (int) (top + min);
}
}
public int getMin() {
return (int) min;
}
}