Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1: Input [“MinStack”,”push”,”push”,”push”,”getMin”,”pop”,”top”,”getMin”] [[],[-2],[0],[-3],[],[],[],[]]
Constraints: -231 <= val <= 231 - 1 Methods pop, top and getMin operations will always be called on non-empty stacks. At most 3 * 104 calls will be made to push, pop, top, and getMin.
最小栈。
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
MinStack() 初始化堆栈对象。 void push(int val) 将元素val推入堆栈。 void pop() 删除堆栈顶部的元素。 int top() 获取堆栈顶部的元素。 int getMin() 获取堆栈中的最小元素。
/** * 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(); */
/** * initialize your data structure here. */ varMinStack = function () { this.stack = []; this.minStack = []; };
/** * @param {number} x * @return {void} */ MinStack.prototype.push = function (x) { this.stack.push(x); if (this.minStack.length) { let top = this.minStack[this.minStack.length - 1]; if (x <= top) { this.minStack.push(x); } } else { this.minStack.push(x); } };
/** * @return {void} */ MinStack.prototype.pop = function () { let pop = this.stack.pop(); let top = this.minStack[this.minStack.length - 1]; if (pop === top) { this.minStack.pop(); } };
/** * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(x) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.getMin() */
publicMinStack() { stack = newStack<>(); min = Integer.MAX_VALUE; }
publicvoidpush(int val) { if (val <= min) { stack.push(min); min = val; } stack.push(val); }
publicvoidpop() { if (stack.pop() == min) { min = stack.pop(); } }
publicinttop() { return stack.peek(); }
publicintgetMin() { return min; } }
/** * 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(); */
/** * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(x) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.getMin() */