请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Stack; class MinStack { private Stack<Integer> rawStack; private Stack<Integer> assistStack; /** initialize your data structure here. */ public MinStack() { this.rawStack = new Stack<>(); this.assistStack = new Stack<>(); } /** * 辅助栈顶维护当前最小元素 * @param x */ public void push(int x) { this.rawStack.push(x); if (this.assistStack.isEmpty() || this.assistStack.peek() >= x) { this.assistStack.push(x); } } public void pop() { Integer pop = this.rawStack.pop(); if (pop.equals(this.assistStack.peek())) { this.assistStack.pop(); } } public int top() { return this.rawStack.peek(); } public int getMin() { return this.assistStack.peek(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */