Look a hundred times beauty, beauty is not necessarily yours. But if you run the algorithm a hundred times, the knowledge is yours

Who can have nine floors? No need to get up!

Title address

The title

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.

Example:

Input: [" RecentCounter ", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] output: [null, 1, 2, 3, 3] :  RecentCounter recentCounter = new RecentCounter(); recentCounter.ping(1); // requests = [1], range [-2999,1], returns 1 recentCounter.ping(100); // requests = [1], range [-2999,1], returns 1 recentCounter.ping(100); // requests = [1, 100] in the range [-2900,100], returns 2 recentCounter.ping(3001); // requests = [1, 100] in the range [-2900,100], returns 2 recentCounter.ping(3001); // requests = [1, 100, 3001] in range [1,3001], return 3 recentCounter.ping(3002); // requests = [1, 100, 3001] in range [1,3001], return 3 recentCounter.ping(3002); // requests = [1, 100, 3001, 3002] in the range [2,3002], return 3Copy the code

Tip:

  • 1 <= t <= 109
  • Make sure that every timepingThat is used by the calltValues areStrictly increasing
  • Up to callpingmethods104 次

Their thinking

  • We’re going to store each time in an arraypingThe value of the
  • It’s not hard to see from the problem that it’s an ascending array
  • Calculate the array in[t-3000, t]The number of elements between

The problem solving code

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

/ * * *@param {number} t
 * @return {number}* /
RecentCounter.prototype.ping = function(t) {
    this.arr.push(t)
    let i = 0
    let [low,high] = [t-3000,t]
    this.arr.forEach(v= >{
        if(v>=low&&v<=high){
            i++
        }
    })
    return i
};
Copy the code

If you have any questions or suggestions, please leave a comment!