前端仔的算法之路(二)-实现一个时间复杂度O(1)的minStack

193 阅读1分钟

实现思路

通过在栈内再维护一个已经降序好的栈,用于读取最小值

ps:时间复杂度O(1)表示耗时与输入数据大小无关,无论输入数据增大多少倍,耗时都不变

class MinStack {
    constructor() {
        // 用于存储数据
        this.stackA = [];
        // 用于存储降序后的数据
        this.stackB = [];

        // 记录栈的数据个数
        this.countA = 0
        this.countB = 0
    }
    
    // 入栈
    push(item) {
        this.stackA[this.countA++] = item
        /*
            这里进行了两个判断
            条件1:栈B为空
            条件2:最小值大于等于传入的数据
                这里之所以是>=而不是大于>,主要是避免如下情况
                stackA:[3, 1, 1]
                stackB: [3, 1]
                进行出栈操作
                stackA:[3, 1]
                stackB: [3]
                可以发现stackB中1被删除了,但其实在stackA中1仍然是最小值
        */
        if (this.countB === 0 || this.min() >= item) {
            this.stackB[this.countB++] = item
        }
    }
    
    // 出栈
    pop() {
        if (this.isEmpty()) {
            return
        }
        // 缓存被删除的数据
        const temp = this.stackA[this.countA - 1]
        delete this.stackA[--this.countA]
        // 只有最小值等于被出栈的值,countB才进行出栈操作
        if (this.min() === temp) {
            delete this.stackB[--this.countB]
        }
        return temp
    }
    
    // 是否为空
    isEmpty() {
        this.countA === 0
    }
    
    // 最小值函数
    min() {
        return this.stackB[this.countB - 1]
    }
  }
  const stack = new MinStack()
  stack.push(10)
  stack.push(7)
  stack.push(8)
  stack.push(7) // stackA:[ 10, 7, 8, 7 ] stackB: [ 10, 7, 7 ]
  stack.min() // 7

前端仔的算法之路(一)-栈基本概念 - 掘金 (juejin.cn)

前端仔的算法之路(三)-利用递减栈实现每日温度 - 掘金 (juejin.cn)