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 ping
s 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 toping
. - Each test case will call
ping
with strictly increasing values oft
. - Each call to ping will have
1 <= t <= 10^9
.
写一个
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]
提示:
- 每个测试用例最多调用
10000
次ping
。 - 每个测试用例会使用严格递增的
t
值来调用ping
。 - 每次调用
ping
都有1 <= t <= 10^9
。
1204ms
1 class RecentCounter { 2 var pq:Queue<Int> = Queue<Int>() 3 4 init() { 5 6 } 7 8 func ping(_ t: Int) -> Int { 9 pq.enQueue(t) 10 while(!pq.isEmpty() && pq.getFirst()! < t-3000) 11 { 12 pq.deQueue() 13 } 14 return pq.count 15 } 16 } 17 18 public struct Queue<T> { 19 20 // 泛型数组:用于存储数据元素 21 fileprivate var queue: [T] 22 23 // 返回队列中元素的个数 24 public var count: Int { 25 return queue.count 26 } 27 28 // 构造函数:创建一个空的队列 29 public init() { 30 queue = [T]() 31 } 32 33 //通过既定数组构造队列 34 init(_ arr:[T]){ 35 queue = arr 36 } 37 38 // 如果定义了默认值,则可以在调用函数时省略该参数 39 init(_ elements: T...) { 40 queue = elements 41 } 42 43 // 检查队列是否为空 44 // - returns: 如果队列为空,则返回true,否则返回false 45 public func isEmpty() -> Bool { 46 return queue.isEmpty 47 } 48 49 // 入队列操作:将元素添加到队列的末尾 50 public mutating func enQueue(_ element: T) { 51 queue.append(element) 52 } 53 54 // 出队列操作:删除并返回队列中的第一个元素 55 public mutating func deQueue() -> T? { 56 return queue.removeFirst() 57 } 58 59 // 返回队列中的第一个元素(不删除) 60 public func getFirst() -> T? { 61 return queue.first! 62 } 63 } 64 65 /** 66 * Your RecentCounter object will be instantiated and called as such: 67 * let obj = RecentCounter() 68 * let ret_1: Int = obj.ping(t) 69 */ 70
原文地址:https://www.cnblogs.com/strengthen/p/9903392.html
时间: 2024-10-06 13:53:10