題目地址:
https://leetcode.com/problems/design-hit-counter/
設計一個數據結構。會接連進來一些數字,代表時間,要求該數據結構能動態查詢過去長度爲的這個時間段來了多少個數字。
思路是隊列,來一個數字就入隊,查詢的時候只需要把隊首的過期的數字刪掉即可。代碼如下:
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時間複雜度,getHits是;空間。