2020-03-23
栈的最小值
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
题解:
思路1: 栈基础
栈数据格式的基本操作
/** * initialize your data structure here. */ var MinStack = function () { this.stack = []; this.index = 0; }; /** * @param {number} x * @return {void} */ MinStack.prototype.push = function (x) { this.stack[this.index++] = x; // 最后一项插入 }; /** * @return {void} */ MinStack.prototype.pop = function () { this.stack.length = this.index - 1; // 通过length减小删除最后一项 this.index--; }; /** * @return {number} */ MinStack.prototype.top = function () { // 返回最后一项 return this.stack[this.index - 1]; }; /** * @return {number} */ MinStack.prototype.getMin = function () { // 获取最小值 return Math.min(...this.stack); }; /** * 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() */