研习算法第二站-队列(javascript版)

252 阅读1分钟

队列简介

  • 一个先进先出的数据结构、保证有序
  • javascript没有队列,可以用array数据结构模拟队列的功能
const queue = [];
// 返回队列长度
queue.push(1);
// 返回队列长度
queue.push(3);
// 返回 1
const item = queue.shift();
// 返回 3
const item = queue.shift();

使用场景

  • 需要先进先出的场景
  • 例如:js异步中的任务队列、计算最近请求次数 WX20211019-232136@2x.png

leetcode-cn.com 算法题实战

完整题目请打开 leetcode

1634657144261.jpg

解题思路

  • 越早发出的请求越早不在最近3000ms内的请求里
  • 符合先进先出,队列解决
var RecentCounter = function() {
    this.queue = [];
};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {
this.queue.push(t)
 // 循环对比 对头数据是否在 t - 3000 
 while(this.queue[0] < t - 3000) {
     this.queue.shift();
 }
 return this.queue.length;
};

/**
 * Your RecentCounter object will be instantiated and called as such:
 * var obj = new RecentCounter()
 * var param_1 = obj.ping(t)
 */

下一站 链表