【Leetcode】362. Design Hit Counter

題目地址:

https://leetcode.com/problems/design-hit-counter/

設計一個數據結構。會接連進來一些數字,代表時間,要求該數據結構能動態查詢過去長度爲300300的這個時間段來了多少個數字。

思路是隊列,來一個數字就入隊,查詢的時候只需要把隊首的過期的數字刪掉即可。代碼如下:

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

public class HitCounter {
    
    private Queue<Integer> queue;
    
    /** Initialize your data structure here. */
    public HitCounter() {
        queue = new LinkedList<>();
    }
    
    /** Record a hit.
     @param timestamp - The current timestamp (in seconds granularity). */
    public void hit(int timestamp) {
        queue.offer(timestamp);
    }
    
    /** Return the number of hits in the past 5 minutes.
     @param timestamp - The current timestamp (in seconds granularity). */
    public int getHits(int timestamp) {
        while (!queue.isEmpty() && queue.peek() <= timestamp - 300) {
            queue.poll();
        }
        
        return queue.size();
    }
}

hit時間複雜度O(1)O(1),getHits是O(n)O(n);空間O(n)O(n)

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