Concept:
- Queues are fifO data structures, as opposed to stacks.
- JavaScript doesn’t have a built-in queue as a data structure, but you can use arrays to simulate it
Conceptual code implementation:
Const queue = [] queue.push(1) queue.shift() // queue outCopy the code
Common uses of queues:
- Anything that needs fifO
- Event loop in JavaScript
Leetcode:
T933. Number of recent requests:
Write a RecentCounter class to count the most recent requests within a specific time range. 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]
Source: LeetCode link: leetcode-cn.com/problems/nu… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Answer:
Since only the requests sent within 3000ms need to be received, all data can be stored in the queue, and only the requests within 3000ms can be kept in the queue, that is, the time t is continuously pushed into the empty queue, and each push is calculated to determine whether the difference between the current T and the t of the first queue exceeds 3000. If the difference exceeds 3000, the queue will be the first queue. Finally, return the length of the queue.
Code implementation:
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
};
/**
* Your RecentCounter object will be instantiated and called as such:
* var obj = new RecentCounter()
* var param_1 = obj.ping(t)
*/
Copy the code