# Queue 解題分享 ## Leetcode 1700. [Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/) ![](https://i.imgur.com/eGx4JM3.png) ### 題目敘述 寫一個 RecentCounter 類來計算特定時間範圍內最近的請求。 請你實現 RecentCounter: * RecentCounter() 初始化計數器,請求數為 0 。 * int ping(int t) 在時間 t 新增一個新請求,其中 t 表示以毫秒為單位的某個時間,並返回過去 3000 毫秒內發生的所有請求數(包括新請求)。確切地說,返回在 [t-3000, t] 內發生的請求數。 ``` input : ["RecentCounter", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] output : [null, 1, 2, 3, 3] ``` ### 解答程式碼 ```c= typedef struct { int *ping; int head; int tail; } RecentCounter; RecentCounter* recentCounterCreate() { RecentCounter *new = (RecentCounter*)malloc(sizeof(RecentCounter)); new->ping = (int*)malloc(sizeof(int) * 10000); new->head = NULL; new->tail = NULL; return new; } int recentCounterPing(RecentCounter* obj, int t) { obj->ping[obj->tail++] = t; while(t - obj->ping[obj->head] > 3000) { obj->head++; } return obj->tail - obj->head; } void recentCounterFree(RecentCounter* obj) { free(obj->ping); free(obj); } ``` ### 程式碼說明 1. 宣告 struct ```c= typedef struct { int *ping; int head; int tail; } RecentCounter; ``` 2. 創立 recentCounter ```c= RecentCounter* recentCounterCreate() { RecentCounter *new = (RecentCounter*)malloc(sizeof(RecentCounter));//開空間給Queue new->ping = (int*)malloc(sizeof(int) * 10000);//開空間給資料用 new->head = NULL; new->tail = NULL; return new; } ``` 3. ```c= int recentCounterPing(RecentCounter* obj, int t) { obj->ping[obj->tail++] = t; while(t - obj->ping[obj->head] > 3000) { obj->head++; } return obj->tail - obj->head; } ``` 4. ```c= void recentCounterFree(RecentCounter* obj) { free(obj->ping);//清除Queue裡的資料 free(obj);//清除Queue之使用空間 } ```