1. 程式人生 > >[Swift Weekly Contest 109]LeetCode933. 最近的請求次數 | Number of Recent Calls

[Swift Weekly Contest 109]LeetCode933. 最近的請求次數 | Number of Recent Calls

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:

  1. Each test case will have at most 10000 calls to ping
    .
  2. Each test case will call ping with strictly increasing values of t.
  3. 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]

提示:

  1. 每個測試用例最多呼叫 10000 次 ping
  2. 每個測試用例會使用嚴格遞增的 t 值來呼叫 ping
  3. 每次呼叫 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