LeetCode 155
最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。 pop() – 删除栈顶的元素。 top() – 获取栈顶元素。 getMin() – 检索栈中的最小元素。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/min-stack
思路
思路比较简单,建立两个栈即可。 特别注意push()中x进minstack栈时条件是<=
代码实现
import java
.util
.Stack
;
class MinStack {
private Stack
<Integer> stack
;
private Stack
<Integer> minstack
;
public MinStack() {
stack
= new Stack<>();
minstack
=new Stack<>();
}
public void push(int x
) {
if (minstack
.isEmpty()||x
<=minstack
.peek()){
minstack
.push(x
);
}
stack
.push(x
);
}
public void pop() {
int x
=stack
.pop();
if(x
==minstack
.peek()){
minstack
.pop();
}
}
public int top() {
return stack
.peek();
}
public int getMin() {
return minstack
.peek();
}
}