题目传送:https://leetcode.cn/problems/min-stack/
运行效率:
代码如下:
class MinStack {
Stack<Integer> stack;
int min;
public MinStack() {
stack = new Stack<>();
min = Integer.MAX_VALUE;
}
public void push(int val) {
stack.push(val);
if(val<min){ //更新最小值
min=val;
}
}
public void pop() {
stack.pop();
//如果弹出栈顶的元素是栈内最小值,
if(!stack.contains(min)){
int minVal=Integer.MAX_VALUE;
//那就要更新最小值
Iterator<Integer> iterator = stack.iterator();
while (iterator.hasNext()){ //从栈里找出新的最小值
Integer next = iterator.next();
if(next<minVal){
minVal=next;
}
}
min=minVal;
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}