挑战 - 每日系列(Algorithm + TypeChallenge)

65 阅读1分钟

算法小白,2024年2月21日,开始挑战在掘金发布“每日”系列。 (节假日可能会出门所以不算) 涉及到算法,type challenge 等,感兴趣的小伙伴可以持续关注督促互勉 🚀🚀🚀

算法

232. 用栈实现队列

题意理解

使用数据结构 栈 来实现数据结构 队列

思路

  • 栈先进后出
  • 队列先进先出
  • 用JS自带的数组实现即可

解题

const MyQueue = function() {
  this.stack = []
  this.size = 0
}

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  let num = this.stack.splice(0, 1)
  num && this.size--
  return num
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
  return this.stack.at(0)
};

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

TypeChallenge

实现类型 AnyOf<T>, 接收一个数组,数组中任意一项为 true,则返回 true

思路

  • 遍历数组每一项
  • 列举所有转换后为 false 的值,判断是否 extends 它们

解题

type Anyof<T extends readonly any[]> = T[number] extends 0 | '' | [] | false | null | undefined | { [key: string]: never } ? false : true