经过率 57.7%数组
题目连接数据结构
题目描述:函数
定义栈的数据结构,请在该类型中实现一个可以获得栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。this
示例:spa
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.prototype
提示:code
各函数的调用总次数不超过 20000 次blog
思路:ip
本题的重点在于将min方法的时间复杂度降为 O(1)(push 及 pop的时间复杂度本就是O(1))leetcode
stackA维护原数组,stackB维护当前状态下栈A中的最小值
1 /*JavaScript*/ 2 /** 3 * initialize your data structure here. 4 */ 5 var MinStack = function() { 6 MinStack.prototype.stackA = [] 7 MinStack.prototype.stackB = [] 8 }; 9 10 /** 11 * @param {number} x 12 * @return {void} 13 */ 14 MinStack.prototype.push = function(x) { 15 this.stackA.push(x) 16 if(!this.stackB.length || x <= this.stackB[this.stackB.length-1]) this.stackB.push(x) 17 }; 18 19 /** 20 * @return {void} 21 */ 22 MinStack.prototype.pop = function() { 23 if(this.stackA.pop() === this.stackB[this.stackB.length-1]) this.stackB.pop() 24 }; 25 26 /** 27 * @return {number} 28 */ 29 MinStack.prototype.top = function() { 30 if(this.stackA.length) return this.stackA[this.stackA.length-1] 31 }; 32 33 /** 34 * @return {number} 35 */ 36 MinStack.prototype.min = function() { 37 if(this.stackB.length) return this.stackB[this.stackB.length-1] 38 }; 39 40 /** 41 * Your MinStack object will be instantiated and called as such: 42 * var obj = new MinStack() 43 * obj.push(x) 44 * obj.pop() 45 * var param_3 = obj.top() 46 * var param_4 = obj.min() 47 */