【Lintcode】505. Web Logger
阿新 • • 發佈:2021-01-09
技術標籤:# 棧、佇列、串及其他資料結構佇列資料結構java演算法leetcode
題目地址:
https://www.lintcode.com/problem/web-logger/description
要求設計一個數據結構實現下面操作:
1、hit(timestamp)
,記錄在該時間有個hit;
2、get_hit_count_in_last_5_minutes(timestamp)
,得到最後
5
5
5分鐘hit個數。
可以用佇列。get的時候把隊頭的過期的hit全出隊。程式碼如下:
import java.util.ArrayDeque;
import java.util.Queue;
public class WebLogger {
private Queue<Integer> queue;
public WebLogger() {
// do intialization if necessary
queue = new ArrayDeque<>();
}
/*
* @param timestamp: An integer
* @return: nothing
*/
public void hit(int timestamp) {
// write your code here
queue.offer(timestamp);
}
/*
* @param timestamp: An integer
* @return: An integer
*/
public int get_hit_count_in_last_5_minutes(int timestamp) {
// write your code here
while (!queue.isEmpty() && queue.peek( ) + 300 < timestamp) {
queue.poll();
}
return queue.size();
}
}
所有操作時間複雜度 O ( 1 ) O(1) O(1),空間 O ( n ) O(n) O(n), n n n是最大 5 5 5分鐘內的總hit個數。