Open songyy5517 opened 5 months ago
Approach: Queue
Complexity Analysis
class RecentCounter {
// Intuition: Queue.
Queue<Integer> queue = null;
public RecentCounter() {
queue = new LinkedList();
}
public int ping(int t) {
// 1. Remove all the elements out of [t-3000, t]
while (!queue.isEmpty() && queue.peek() < t - 3000)
queue.remove();
// 2. Add the new element to the queue
queue.add(t);
return queue.size();
}
}
2024/5/24
You have a RecentCounter class which counts the number of recent requests within a certain time frame.
Implement the RecentCounter class:
RecentCounter()
Initializes the counter with zero recent requests.int ping(int t)
Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
Example 1:
Intuition Basically, given a series of t, the problem is to keep all the previous elements within the range of [t-3000, t]. From the description, we know that t is always greater the preceding one. Therefore, we can use a queue to store these ts, and remove the out-of-range elements from the end of queue.