队列 滑动窗口
方法一队列
由于数据是严格递增的,创建一个队列,先进的是小的时间,先进去的时间优先出来,这样队列里面保存的就是最近的3000的数据
参考代码
class RecentCounter:def __init__(self):self.q = collections.deque()def ping(self, t: int) -> int:self.q.append(t)while t - self.q[0] > 3000:self.q.popleft()return len(self.q)# Your RecentCounter object will be instantiated and called as such:# obj = RecentCounter()# param_1 = obj.ping(t)
复杂度分析
时间复杂度 O(1) 遍历找到最近3000个数的操作为最多为3000不会随数据规模扩大而扩大。
空间复杂度 O(m)
方法二滑动窗口
参考代码
class RecentCounter:def __init__(self):self.arr = []self.left = 0def ping(self, t: int) -> int:self.arr.append(t)while t - self.arr[self.left] > 3000:self.left += 1return len(self.arr) - self.left# Your RecentCounter object will be instantiated and called as such:# obj = RecentCounter()# param_1 = obj.ping(t)
复杂度分析
时间复杂度 O(1)
空间复杂度 O(n) n为数据规模,即调用次数
