Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

First, understand the topic

933. Number of recent requests

Write a RecentCounter class to count the most recent requests within a specific time range.

Please implement RecentCounter class:

RecentCounter() initializes the counter with 0 requests.

Int ping(int t) adds a new request at time t, where t represents some time in milliseconds, and returns the number of all requests (including new requests) that occurred in the last 3000 milliseconds. Specifically, return the number of requests that occurred within [T-3000, t].

Make sure that each call to ping uses a larger t value than before.

Ii. Solution analysis

(1) How to solve the problem

  • The earlier the request is made, the sooner it is not recent3000msIn the request of;
  • First in, first out, queue.

(2) Steps to solve the problem

  • New requests to join the team;
  • Requests made before 3000 milliseconds are queued.

Three, code implementation

Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:

let RecentCounter = function () {
    this.queue = [];
}
​
RecentCounter.prototype.ping = function (t) {
    // 1. The number of new requests must be the last
    this.queue.push(t);
    // 2. If the value is less than, the value is removed
    while (this.queue[0] < t - 3000) {
        // 2.1 Removes the first element of the array and returns it
        this.queue.shift();
    }
    // 3. Return the number of requests in 3000s
    return this.queue.length;
}
​
let obj = new RecentCounter();
​
obj.ping(1);
obj.ping(1);
obj.ping(100);
obj.ping(3001);
obj.ping(3002);
​
console.log(obj); // RecentCounter { queue: [ 100, 3001, 3002 ] }
Copy the code

The above is about the number of recent requests, do not know whether it is helpful to friends?

We’ll see you next time at 👋👋👋