栈&队列算法小结【JS】

66 阅读1分钟

栈和队列算法汇总

用栈实现队列

leetcode.cn/problems/im…

/**
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
  this.stackIn.push(x)
  this.size++
}

/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {
  this.size--
  if (this.stackOut.length) {
    return this.stackOut.pop()
  }
  while (this.stackIn.length) {
    this.stackOut.push(this.stackIn.pop())
  }
  return this.stackOut.pop()
}

/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
  if (this.stackOut.length) {
    return this.stackOut[this.stackOut.length - 1]
  }
  return this.stackIn[0]
}

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
  return this.size === 0
}

用队列实现栈

leetcode.cn/problems/im…

var MyStack = function () {
  this.queue = []
  this.size = 0
}

/**
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
  this.queue.push(x)
  this.size++
}

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
  for (let i = 0; i < this.size - 1; i++) {
    this.queue.push(this.queue.shift())
  }
  this.size--
  return this.queue.shift()
}

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
  const val = this.pop()
  this.push(val)
  return val
}

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
  return this.size === 0
}

有效的括号

leetcode.cn/problems/va…

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function (s) {
  const stack = []
  for (let i = 0; i < s.length; i++) {
    if (['(', '[', '{'].includes(s[i])) {
      stack.push(s[i])
    } else if (s[i] === ')') {
      if (stack[stack.length - 1] === '(') {
        stack.pop()
      } else {
        return false
      }
    } else if (s[i] === ']') {
      if (stack[stack.length - 1] === '[') {
        stack.pop()
      } else {
        return false
      }
    } else if (s[i] === '}') {
      if (stack[stack.length - 1] === '{') {
        stack.pop()
      } else {
        return false
      }
    }
  }
  return stack.length === 0
}

删除字符串中的所有相邻重复项

leetcode.cn/problems/re…

/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicates = function (s) {
  const stack = []
  for (let i = 0; i < s.length; i++) {
    if (s[i] === stack[stack.length - 1]) {
      stack.pop()
    } else {
      stack.push(s[i])
    }
  }
  return stack.join('')
}

逆波兰表达式求值

leetcode.cn/problems/ev…

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function (tokens) {
  const operators = ['+', '-', '*', '/']
  const stack = []
  for (let i = 0; i < tokens.length; i++) {
    if (!operators.includes(tokens[i])) {
      stack.push(Number(tokens[i]))
    } else {
      const num2 = stack.pop()
      const num1 = stack.pop()
      switch (tokens[i]) {
        case '+':
          stack.push(num1 + num2)
          break
        case '-':
          stack.push(num1 - num2)
          break
        case '*':
          stack.push(num1 * num2)
          break
        case '/':
          stack.push(Math.trunc(num1 / num2))
          break
        default:
          break
      }
    }
  }
  return stack[0]
}

滑动窗口最大值

leetcode.cn/problems/sl…

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var maxSlidingWindow = function (nums, k) {
  class MonoQueue {
    constructor() {
      this.queue = []
    }
    enQueue(val) {
      while (this.queue[this.queue.length - 1] < val) {
        this.queue.pop()
      }
      this.queue.push(val)
    }
    deQueue(val) {
      if (this.queue[0] === val) {
        this.queue.shift()
      }
    }
    getMax() {
      return this.queue[0]
    }
  }
  const res = []
  const monoQueue = new MonoQueue()
  for (let i = 0; i < nums.length; i++) {
    if (i < k - 1) {
      monoQueue.enQueue(nums[i])
      continue
    }
    monoQueue.enQueue(nums[i])
    monoQueue.deQueue(nums[i - k])
    res.push(monoQueue.getMax())
  }
  return res
}

前 K 个高频元素

leetcode.cn/problems/to…

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function (nums, k) {
  const res = []
  const map = new Map()
  for (let i = 0; i < nums.length; i++) {
    map.set(nums[i], map.get(nums[i]) + 1 || 1)
  }
  const mapArr = Array.from(map).sort((a, b) => b[1] - a[1])
  return mapArr.slice(0, k).map((i) => i[0])
}