classMinStack{ // 这个作为主栈 Stack<Integer> s1 = new Stack<>(); // 这个作为辅助栈,放最小值的栈 Stack<Integer> s2 = new Stack<>(); /** initialize your data structure here. */ publicMinStack(){
}
publicvoidpush(int x){ // 放入主栈 s1.push(x); // 当 s2 是空或者当前值是小于"等于" s2 栈顶时,压入辅助最小值的栈 // 注意这里的"等于"非常必要,因为当最小值有多个的情况下,也需要压入栈,否则在 pop 的时候就会不对等 if (s2.isEmpty() || x <= s2.peek()) { s2.push(x); } }
publicvoidpop(){ // 首先就是主栈要 pop,然后就是第二个了,跟上面的"等于"很有关系, // 因为如果有两个最小值,如果前面等于的情况没有压栈,那这边相等的时候 pop 就会少一个了,可能就导致最小值不对了 int x = s1.pop(); if (x == s2.peek()) { s2.pop(); } }