queue: 先进先出,对应 push, shift 操作

例题

1.最近请求次数

image.png
最近请求次数
题意:持续往队列里 push 请求,只保留相隔时间在3000毫秒之内的请求

  1. var RecentCounter = function () {
  2. // 创建一个队列,存放所有请求
  3. this.queue = [];
  4. };
  5. /**
  6. * @param {number} t
  7. * @return {number}
  8. */
  9. RecentCounter.prototype.ping = function (t) {
  10. // 先将请求传入队列 queue
  11. this.queue.push(t);
  12. // 判断列头是否在3000毫秒之内,否则弹出,用 while 循环弹出所有不符合的
  13. while (this.queue[0] + 3000 < t) {
  14. this.queue.shift();
  15. }
  16. return this.queue.length;
  17. };