leeCode算法--实现最小栈操作

题目:设计一个支持 push,pop,top操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素。
    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
    let MinStack = function () {
    this.data = []
    }
    MinStack.prototype.push = function (x) {
    this.data.push(x)
    }
    MinStack.prototype.pop() = function () {
    this.data.pop()
    }
    MinStack.prototype.top = function () {
    if (!this.data.length) return
    return this.data.slice(this.data.length - 1, this.data.length)
    }
    MinStack.prototype.getMin = function () {
    let num = this.data[0]
    for (let i = 1; i < this.data.length;i++) {
    if (num >= this.data[i]) {
    num = this.data[i]
    }
    }
    return num
    }
    let stack = new MinStack()
    stack.push(3)
    stack.push(1)
    stack.push(5)
    stack.push(2)
    stack.push(4)
    stack.pop() // 4
    stack.top() // 2
    stack.getMin() // 1
    That’s all.
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2022 Lee
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信