美文网首页
155. Min Stack

155. Min Stack

作者: jluemmmm | 来源:发表于2021-08-10 00:41 被阅读0次

设计一个支持push、pop、top、在常数时间内检索最小元素的栈。

解法: 数组存储元素的值和小于当前栈中最小元素的值

  • 时间复杂度 O(1),空间复杂度O(N)
  • Runtime: 124 ms, faster than 49.61%
  • Memory Usage: 47.6 MB, less than 22.40%
function last(arr) {
  return arr[arr.length - 1];
}

/** 
 * Your MinStack object will be instantiated and called as such:
 * var obj = new MinStack()
 * obj.push(val)
 * obj.pop()
 * var param_3 = obj.top()
 * var param_4 = obj.getMin()
 */


class MinStack {
  constructor () {
    this.stack = []
  }
  
  push(x) {
    if (this.stack.length === 0) {
      this.stack.push([x, x]);
      return;
    }
    
    const currentMin = last(this.stack)[1];
    this.stack.push([x, Math.min(currentMin, x)])
  }
  pop() {
    this.stack.pop()
  }
  top() {
    return last(this.stack)[0]
  }
  getMin() {
    return last(this.stack)[1]
  }
}

相关文章

  • leetcode:155. Min Stack

    155. Min Stack Description Design a stack that supports p...

  • Leetcode-155Min Stack

    155. Min Stack && 剑指offer-包含min函数的栈 Design a stack that s...

  • 155. Min Stack

    Design a stack that supports push, pop, top, and retrievi...

  • 155. Min Stack

    Problem Design a stack that supports push, pop, top, and ...

  • 155. Min Stack

    Description: Design a stack that supports push, pop, top,...

  • 155. Min Stack

    1.描述 Design a stack that supports push, pop, top, and ret...

  • 155. Min Stack

    题目 Design a stack that supports push, pop, top, and retri...

  • 155. Min Stack

    Description: Design a stack that supports push, pop, top,...

  • 155. Min Stack

    Design a stack that supports push, pop, top, and retrievi...

  • 155. Min Stack

    Design a stack that supports push, pop, top, and retrievi...

网友评论

      本文标题:155. Min Stack

      本文链接:https://www.haomeiwen.com/subject/ojatbltx.html