Given constant integers x and t, write a function that takes no argument and returns true if the function has been called x number of times in last t secs.
随便写了一下,看得懂就好。主要思想是使用队列,被call了就入队,满了就头出队,队列存clock_t数据。
#include <time.h>
#include <queue>
std::queue<clock_t> calls;
const int X = 10;
const int T = 80;
bool called()
{
bool wasCalled = false;
clock_t curTime = clock();
clock_t oldTime = curTime - T * CLOCKS_PER_SEC;
if(calls.size() == X)
{
if(calls.front() >= oldTime)
wasCalled = true;
calls.pop();
}
calls.push(curTime);
return wasCalled;
}
int main()
{
for(int i = 0; i < 10; i++)
called();
bool b = called();
if(b)
printf("YES");
return 0;
}
本文介绍了一种基于队列的算法实现方案,用于检测一个函数是否在最近特定秒数内被调用过指定次数。该算法利用了clock_t类型记录时间,并通过队列维护最近的调用记录。
1093

被折叠的 条评论
为什么被折叠?



