题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
——来源于《剑指offer》
- 刚看到这个题想的是用一个全局变量来保存最小值min,每次push的时候判断一下,如果比最小值小,就将最小值替换为更小的那个数。但是这个思路有很大的问题,就是当我们pop一个元素的时候无法知道上一个最小的数是多少,无法更新最小数。
class MyStackDemo {
private Stack<Integer> s = new Stack<>();
private Integer min = null;
public void push(Integer i) {
if (min == null || min > i) {
min = i;
}
s.push(i);
}
public Integer pop() {
return s.pop();
}
public Integer min() {
return min;
}
}
- 于是我们不仅要保存最小的数,还要保存每次push的时候对应的最小的数,于是有了下面的代码:
import java.util.Stack;
public class Solution {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
public void push(int node) {
s1.push(node);
if (s2.empty() || s2.peek() > node) {
s2.push(node);
} else {
s2.push(s2.peek());
}
}
public void pop() {
s2.pop();
s1.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}