【Leetcode】933. Number of Recent Calls

題目地址:

https://leetcode.com/problems/number-of-recent-calls/

有一組輸入,是一些正整數,代表請求到達的時間tt。要求動態返回[t3000,t][t-3000,t]這個區間內有多少個請求。題目保證tt是嚴格遞增排列的。

思路是隊列,來一個請求就將其時間入隊,然後把隊裏過時的請求出隊,最後返回隊列的size即可。代碼如下:

import java.util.LinkedList;
import java.util.Queue;

public class RecentCounter {
    
    private Queue<Integer> queue;
    
    public RecentCounter() {
        queue = new LinkedList<>();
    }
    
    public int ping(int t) {
        queue.offer(t);
        while (t - queue.peek() > 3000) {
            queue.poll();
        }
        
        return queue.size();
    }
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章