leetcode933題.最近的請求次數
阿新 • • 發佈:2022-05-06
寫一個 RecentCounter 類來計算特定時間範圍內最近的請求。
請你實現 RecentCounter 類:
RecentCounter() 初始化計數器,請求數為 0 。
int ping(int t) 在時間 t 新增一個新請求,其中 t 表示以毫秒為單位的某個時間,並返回過去 3000 毫秒內發生的所有請求數(包括新請求)。確切地說,返回在 [t-3000, t] 內發生的請求數。
保證 每次對 ping 的呼叫都使用比之前更大的 t 值。
//例項一 輸入: ["RecentCounter", "ping", "ping", "ping", "ping"] [[], [1], [100], [3001], [3002]] 輸出: [null, 1, 2, 3, 3] 解釋: RecentCounter recentCounter = new RecentCounter(); recentCounter.ping(1); // requests = [1],範圍是 [-2999,1],返回 1 recentCounter.ping(100); // requests = [1, 100],範圍是 [-2900,100],返回 2 recentCounter.ping(3001); // requests = [1, 100, 3001],範圍是 [1,3001],返回 3 recentCounter.ping(3002); // requests = [1, 100, 3001, 3002],範圍是 [2,3002],返回 3
首先先複習一下二分法
public class Solution{ static int binarySearch(int[]arr,int item){ int index=-1; int low=0,high=arr.length-1; while(low<=high){ int mid=(low+high)/2; if(arr[mid]==item) return mid; else if(arr[mid]<item) low=mid+1;else high=mid-1; } return index; } }
方法一:使用佇列
class RecentCounter {
//利用佇列先進先出的特性,對最先插入佇列的元素進行操作 Queue<Integer> queue; public RecentCounter() { queue=new ArrayDeque<>(); } public int ping(int t) { queue.offer(t); while(queque.peek()+3000<t){ queue.poll(); } return queue.size(); } }
方法二:滑動視窗
class RecentCounter { int[]arr; int tail,head; public RecentCounter() { arr=new int[10240]; tail=head=0; } public int ping(int t) { arr[tail++]=t; while(tail>head&&arr[head]+3000<t){ head++; } return tail-head; } }
方法三:二分法查詢法
class RecentCounter { List<Integer>list; public RecentCounter() { list=new ArrayList<>(); } public int ping(int t) { list.add(t); if(t<=3000) return list.size(); else{ int idx=findIndex(list,t-3000); return l } } int findIndex(List<Integer>list,int item){ int left=0,right=list.size()-1; while(left<=right){ int mid=(left+right)>>1; if(list.get(mid)==item) return mid; else if(list.get(mid)>item) right=mid-1; else left=mid+1; } return left; } }