【Leetcode刷题笔记】队列

目录

    • 一、最近的请求次数

一、最近的请求次数

【题号】933
【题目描述】
写一个 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]
【常规解法】
我们只会考虑最近 3000 毫秒到现在的 ping 数,因此我们可以使用队列存储这些 ping 的记录。当收到一个时间 t 的 ping 时,我们将它加入队列,并且将所有在时间 t - 3000 之前的 ping 移出队列。
【我的代码】

class RecentCounter(object):

    def __init__(self):
        self.queen=[]

    def ping(self, t):
        """
        :type t: int
        :rtype: int
        """
        self.queen.append(t)
        while(self.queen[0]<t-3000):
            self.queen.pop(0)
        return len(self.queen)
                 
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)

【执行情况】
在这里插入图片描述
【范例代码】

class RecentCounter(object):
    def __init__(self):
        self.q = collections.deque()

    def ping(self, t):
        self.q.append(t)
        while self.q[0] < t-3000:
            self.q.popleft()
        return len(self.q)

作者:LeetCode
链接:https://leetcode-cn.com/problems/number-of-recent-calls/solution/zui-jin-de-qing-qiu-ci-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

【分析】
解法和代码基本和范例一样。因为ping的时间序列是单增的,即距离当前时间越久的Ping在统计时是越不需要考虑的,所以可以把之前的ping出队。

你可能感兴趣的:(leetcode)