933 Number of Recent Calls 最近的請(qǐng)求次數(shù)
Description:
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:
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 to ping.
Each test case will call ping with strictly increasing values of t.
Each call to ping will have 1 <= t <= 10^9.
題目描述:
寫一個(gè) RecentCounter 類來計(jì)算最近的請(qǐng)求。
它只有一個(gè)方法:ping(int t),其中 t 代表以毫秒為單位的某個(gè)時(shí)間。
返回從 3000 毫秒前到現(xiàn)在的 ping 數(shù)。
任何處于 [t - 3000, t] 時(shí)間范圍之內(nèi)的 ping 都將會(huì)被計(jì)算在內(nèi),包括當(dāng)前(指 t 時(shí)刻)的 ping。
保證每次對(duì) ping 的調(diào)用都使用比之前更大的 t 值。
示例 :
輸入:inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
輸出:[null,1,2,3,3]
提示:
每個(gè)測(cè)試用例最多調(diào)用 10000 次 ping。
每個(gè)測(cè)試用例會(huì)使用嚴(yán)格遞增的 t 值來調(diào)用 ping。
每次調(diào)用 ping 都有 1 <= t <= 10^9。
思路:
維護(hù)一個(gè)長(zhǎng)度為 3000的滑動(dòng)窗口, 可用隊(duì)列實(shí)現(xiàn)
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class RecentCounter
{
public:
RecentCounter() {}
int ping(int t)
{
q.push(t);
while (t - 3000 > q.front()) q.pop();
return q.size();
}
private:
queue<int> q;
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/
Java:
class RecentCounter {
private Queue<Integer> queue;
public RecentCounter() {
queue = new LinkedList<>();
}
public int ping(int t) {
queue.offer(t);
while (queue.peek() < t - 3000) queue.poll();
return queue.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
Python:
class RecentCounter:
def __init__(self):
self.queue = collections.deque()
def ping(self, t: int) -> int:
self.queue.append(t)
while self.queue[0] < t - 3000:
self.queue.popleft()
return len(self.queue)
# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)