用队列 Deque 。
从队列头部开始遍历,判断头部元素是否小于 (当前值t - 3000),如果是,则删除该头部元素。
最后,将 t 添加到队尾。
#include <iostream>
#include <algorithm>
#include "vector"
#include "string"
#include "set"
#include "queue"
using namespace std;
class RecentCounter
{
public:
queue<int>q;
RecentCounter()
{
}
int ping(int t)
{
/*if (t < 3000)
{
return t;
}*/
while (!q.empty() && t - q.front() > 3000)
{
q.pop();
}
q.push(t);
return q.size();
}
};
int main()
{
RecentCounter* obj = new RecentCounter();
int param_1 = obj->ping(3001);
system("pause");
return 0;
}