Offer_155 最小栈
// 空间换时间、利用两个栈进行存储,加入时候注意,如果当前值等于最小栈的栈顶元素,也需要加入
class MinStack { Stack<Integer> stack1; Stack<Integer> stack2; public MinStack() { stack1 = new Stack<>(); stack2 = new Stack<>(); } public void push(int val) { stack1.push(val); // 在等于的时候,也需要加入当前加入的值,在后续退出的时候,可以又两个值。 if (stack2.isEmpty() || stack2.peek() >= val) { stack2.push(val); } } public void pop() { if (!stack1.isEmpty()) { int top = stack1.pop(); if (top == stack2.peek()) { stack2.pop(); } } } public int top() { if (!stack1.isEmpty()) { return stack1.peek(); } return 0; } public int getMin() { if (!stack2.isEmpty()) { return stack2.peek(); } return 0; } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(val); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
参考链接 : https://www.cnblogs.com/Curryxin/p/15135700.html

浙公网安备 33010602011771号