“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
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.
Source: LeetCode leetcode-cn.com/problems/nu…
Their thinking
- Returns the number of requests;
- Returns the number of requests that occurred in the last 3000 milliseconds, so that when a new request comes in, any request that is more than 3000 milliseconds later can be removed.
- So we can do this with a queue, where new requests come in and the ones that don’t meet the criteria get queued out;
- Finally returns the queue length;
Code implementation
Var RecentCounter = function() {this.queue = new Array()}; / * * * @ param @ return {number} {number} t * * / RecentCounter prototype. Ping = function (t) {/ / the current time in queue. This queue. Push (t) While (this.queue.length && this.queue[0] < t-3000) {this.queue.shift()} // Return the length of the queue this.queue.length };Copy the code
If there are mistakes welcome to point out, welcome to discuss together!