經過率 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 */