Number of Recent Calls
Problem
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 timet
, wheret
represents some time in milliseconds, and returns the number of requests that has happened in the past3000
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.
Constraints
1 <= t <= 109
- Each test case will call
ping
with strictly increasing values oft
. - At most
104
calls will be made toping
.
Solution
The problem Number of Recent Calls
can be solved by storing the time of each calls in a queue and popping every records that happened before the past 3000
milliseconds of a given call.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class RecentCounter
{
private:
queue<int> calls;
public:
RecentCounter() {}
int ping(int t)
{
calls.push(t);
while (calls.front() < t - 3000)
calls.pop();
return calls.size();
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/