找到数组中第一个满足条件的元素或下标

写一个 RecentCounter 类来计算特定时间范围内最近的请求。

请实现 RecentCounter 类:

RecentCounter() 初始化计数器,请求数为 0 。
int ping(int t) 在时间 t 添加一个新请求,其中 t 表示以毫秒为单位的某个时间,并返回过去 3000 毫秒内发生的所有请求数(包括新请求)。确切地说,返回在 [t-3000, t] 内发生的请求数。
保证 每次对 ping 的调用都使用比之前更大的 t 值。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/H8086Q

找到数组中第一满足条件的
const arr = [1, 100, 3001, 3002];
const findItem = arr.find(item => item === 100) // 返回子项
const findIndex = arr.findIndex(item => item === 100) // 返回子项的下标

使用数组的findIndex方法 找到第一个大于等于t-3000 的元素

var RecentCounter = function() {
    this.time = [];
};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {
    const min = t -3000;
    this.time.push(t);
    const findIndex = this.time.findIndex(item => item >= min)
    const len = this.time.length - findIndex;
    return len;
};

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

队列

// 定义队列,存放请求的时刻
// 每次发起请求时,先将新的请求时刻t入队
// 再循环判断队头的数,是否小于t-3000,若小于,队头出队。这样就可以将3000 ms以外的时刻全部去除
// 循环完毕,返回队列长度
var RecentCounter = function() {
    this.queue = [];
};

/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {
    this.queue.push(t);
    while (this.queue[0] < t - 3000) {
        this.queue.shift();
    }
    return  this.queue.length;
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值