933. Number of Recent Calls

Link: https://leetcode.com/problems/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 都將計數,包括當前 ping。 保證每次調用 ping 都使用比之前嚴格更大的 t 值。

程式思路:
用一個 deque 容器將時間存起來,為了方便查找所以每次都會從第一個元素開始判斷是否有在 t-3000 時間以內,如果沒有就刪除元素,最後返回容器的總元素量就是答案。

class RecentCounter {
public:
    deque <int> pings;
    RecentCounter() {
    }
    int ping(int t) {
        pings.emplace_back(t);
        for(auto it = pings.begin();it != pings.end();it++)
        {
            if((*it >= t - 3000))
            {
                pings.erase(pings.begin(),it);
                break;
            }
        }
        return pings.size();
    }
};

/**
 * Your RecentCounter object will be instantiated and called as such:
 * RecentCounter* obj = new RecentCounter();
 * int param_1 = obj->ping(t);
 */

  目錄