The description of 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 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.
来源:力扣(LeetCode)
链接:https:
The codes for this problem
#include <vector>
#include <iostream>
using namespace std;
class RecentCounter {
vector<int> records;
int res;
public:
RecentCounter() {
res = 0;
}
int ping(int t) {
records.emplace_back(t);
while (records.front() < t - 3000) {
records.erase(records.begin());
}
res = records.size();
return res;
}
};
int main()
{
RecentCounter* obj = new RecentCounter();
int param_1 = obj->ping(1);
cout << param_1 << endl;
param_1 = obj->ping(100);
cout << param_1 << endl;
param_1 = obj->ping(3001);
cout << param_1 << endl;
param_1 = obj->ping(3002);
cout << param_1 << endl;
return 0;
}
The corresponding results
1
2
3
3
|