[Swift Weekly Contest 109]LeetCode933. 最近的请求次数 | Numb
Write a class? It has only one method:? Return the number of? Any ping with time in? It is guaranteed that every call to? Example 1: Input: inputs = ["RecentCounter","ping","ping"],inputs = [[],[1],[100],[3001],[3002]] Output: [null,1,2,3,3]
Note:
写一个? 它只有一个方法: 返回从 3000 毫秒前到现在的? 任何处于? 保证每次对? 示例: 输入:inputs = ["RecentCounter",inputs = [[],[3002]] 输出:[null,3] 提示:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |