题解 | #包含min函数的栈#
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
import java.util.*; import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); if(stack2.isEmpty() || node<=stack2.peek()) stack2.push(node); } public int pop() { int popValue = stack1.pop(); if(popValue==stack2.peek()) stack2.pop(); return popValue; } public int top() { return stack1.peek(); } public int min() { return stack2.peek(); } }
关于两个栈的同步弹出,我用的是判断是否顶部元素相等。
另一种方法是,不断用相同值入最小值栈, belike:
else s2.push(s2.peek());