题源: leetcode(https://leetcode-cn.com/problems/number-of-recent-calls/)
题目描述:
写一个 RecentCounter 类来计算最近的请求。
它只有一个方法:ping(int t),其中 t 代表以毫秒为单位的某个时间。
返回从 3000 毫秒前到现在的 ping 数。
任何处于 [t - 3000, t] 时间范围之内的 ping 都将会被计算在内,包括当前(指 t 时刻)的 ping。
保证每次对 ping 的调用都使用比之前更大的 t 值。
思路: 使用一个队列,维持队列中最后一个加入的元素和队列头元素加入的时刻差值小于等于3000即可,返回队列元素个数。
class RecentCounter {
private:
queue<int> inputs;
public:
RecentCounter() {
}
int ping(int t) {
// 时间进队列
inputs.push(t);
// 移除队列中 3 秒之前的时间
while(!inputs.empty() && (t - 3000)>inputs.front()) inputs.pop();
// 返回队列中在范围内的个数
return inputs.size();
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/