Bloomberg 面试题05032012[1]

本文介绍了一种基于队列的算法实现方案,用于检测一个函数是否在最近特定秒数内被调用过指定次数。该算法利用了clock_t类型记录时间,并通过队列维护最近的调用记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值