今天带来的是一道简单的LeetCode题,废话少说,直接看题。
不学习,你就废了。
链接:最近的请求次数
Write a class RecentCounter to count recent requests.
It has only one method: ping(int t), where t represents some time in milliseconds.
Return the number of pings that have been made from 3000 milliseconds ago until now.
Any ping with time in [t - 3000, t] will count, including the current ping.
It is guaranteed that every call to ping uses a strictly larger value of t than before.
Example 1:
Input: inputs = [“RecentCounter”,“ping”,“ping”,“ping”,“ping”], inputs = [[],[1],[100],[3001],[3002]]
Output: [null,1,2,3,3]
Note:
Each test case will have at most 10000 calls to ping.
Each test case will call ping with strictly increasing values of t.
Each call to ping will have 1 <= t <= 10^9.
题目大意
这道题的很多人都看不懂,然后就切换到中文版,结果还是看不懂,中文版的翻译如下:
当然,还是有很多人看不懂这道题,如同这些网友的评论:
不过我觉得还好,可能是我之前面试时写过LRU,多看几遍就可以明白题目的意思了。
题目就是让我们获取最近的请求次数,而最近的请求次数其实就是最近3000ms内的请求次数。联系实际应用,既然要获取最近3000ms内的请求,那我们肯定需要用到时间,比如记录当前请求的时间戳,题目没有类似时间戳的东西,但是给我们提供了一个参数t,ping(int t)
这个t我们可以理解为时间戳。
再举个容易懂的例子
2020年01月08日09:00:00
请求了第一次,每次请求时就会返回当前的请求次数,即为1。伪代码的表示为int count = ping("2020年01月08日09:00:00")
,此时的count为12020年01月08日09:00:01
请求了第二次,伪代码的表示为int count = ping("2020年01月08日09:00:01")
,此时的count为22020年01月08日09:00:02
请求了第三次,伪代码的表示为int count = ping("2020年01月08日09:00:02")
,此时的count为32020年01月08日09:00:10
请求了第四次,大家觉得count为多少?(请读者思考一下)09:00:10
请求的,上一次请求是在09:00:02
,已经过去了8s,不属于最近的范围[2020年01月08日09:00:07
, 2020年01月08日09:00:10
]之中。而题目中的t值,其实可以等同于2020年01月08日09:00:00
这个具体的时间。
能理解题意就好办了,我们可以使用一个队列,将每次请求的时间t入队。将过期的时间出队。
入队的话,其实就是queue.offer(t);
的过程,那么出队的话,就需要判断队头的时间是否过期,即队头时间是否在最近时间范围内[t - 3000, t]
class RecentCounter {
private Queue<Integer> queue;
public RecentCounter() {
queue = new LinkedList<Integer>();
}
public int ping(int t) {
while (queue.size() != 0 && queue.peek() < t - 3000)
queue.poll();
queue.offer(t);
return queue.size();
}
}
构造函数实现了对queue的初始化,这里使用了Queue队列数据结构。
在ping函数中,我首先判断了queue是否不为空,且队头元素是否过期,如果过期就将其移出队列,还是很好理解的。
while (queue.size() != 0 && queue.peek() < t - 3000)
queue.poll();
当然,每个t值我们都需要入队,这也是下面这行代码的作用,也是挺好理解的。
queue.offer(t);
最后返回队列的大小,实际上就是返回了请求次数,提交代码,成功!
其实也不算思路2,只是对思路1代码的改进。
我们可以调整一下入队和出队的顺序,首先入队,然后直接判断t值是否符合最近情况,这时候就不需要判断队列是否为空了,看代码吧。
class RecentCounter {
private Queue<Integer> queue;
public RecentCounter() {
queue = new LinkedList<Integer>();
}
public int ping(int t) {
queue.offer(t);
while (queue.peek() < t - 3000)
queue.poll();
return queue.size();
}
}
这里面减少了一个判断空的条件,理论上来说,时间会有些提升,因为不用每次判断2次了,提交代码,OK!
不断学习,加油啦⛽️!