剑指 Offer 30. 包含min函数的栈
题目描述: 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.min(); –> 返回 -3. minStack.pop(); minStack.top(); –> 返回 0. minStack.min(); –> 返回 -2.
思路: 两个栈: 一个栈存放全部的元素,push,pop都是正常操作这个正常栈。 另一个存放最小栈。 每次push,如果比最小栈的栈顶还小,我们就push进最小栈,否则不操作 每次pop的时候,我们都判断其是否和最小栈栈顶元素相同,如果相同,那么我们pop掉最小栈的栈顶元素即可
关键点: 往minstack中 push的判断条件。 应该是stack为空或者x小于等于minstack栈顶元素
代码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 var MinStack = function ( ) { this .stack = [] this .minStack = [] }; MinStack.prototype.push = function (x ) { this .stack.push(x) if (this .minStack.length == 0 || x<=this .minStack[this .minStack.length - 1 ]) { this .minStack.push(x) } }; MinStack.prototype.pop = function ( ) { const x = this .stack.pop() if (x !== void 0 && x === this .minStack[this .minStack.length - 1 ]) { this .minStack.pop() } }; MinStack.prototype.top = function ( ) { return this .stack[this .stack.length - 1 ] }; MinStack.prototype.min = function ( ) { return this .stack[this .stack.length - 1 ] }; MinStack.prototype.min = function ( ) { return this .minStack[this .minStack.length - 1 ] };