内容简介:题目地址:题目描述:
题目地址:
https://leetcode-cn.com/probl...
题目描述:
写一个 RecentCounter 类来计算最近的请求。
它只有一个方法:ping(int t),其中 t 代表以毫秒为单位的某个时间。
返回从 3000 毫秒前到现在的 ping 数。
任何处于 [t - 3000, t] 时间范围之内的 ping 都将会被计算在内,包括当前(指 t 时刻)的 ping。
保证每次对 ping 的调用都使用比之前更大的 t 值。
示例:
输入:inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
输出:[null,1,2,3,3]
解答:
使用一个list来存储请求的时间,每一次调用ping函数,先把这次时间存入list中,然后查找list中所有和当前时间差大于3000的项并删除。接着返回list的大小即可。注:因为这里经常删除,所以用LinkedList的效率会更高一些(ArrayList会挪动元素)。并且删除要用iterator迭代器来删除,否则会引发ConcurrentModificationException。
java ac代码:
class RecentCounter {
List<Integer>list = new LinkedList();
public RecentCounter() {
}
public int ping(int t) {
list.add(t);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext())
{
Integer a = iterator.next();
if(t-a > 3000)
iterator.remove();
else break;
}
return list.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Django 1.0 Template Development
Scott Newman / Packt / 2008 / 24.99
Django is a high-level Python web application framework designed to support the rapid development of dynamic websites, web applications, and web services. Getting the most out of its template system a......一起来看看 《Django 1.0 Template Development》 这本书的介绍吧!