leetcode933. 最近的请求次数
生活随笔
收集整理的這篇文章主要介紹了
leetcode933. 最近的请求次数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
寫一個 RecentCounter 類來計算最近的請求。
它只有一個方法:ping(int t),其中 t 代表以毫秒為單位的某個時間。
返回從 3000 毫秒前到現在的 ping 數。
任何處于 [t - 3000, t] 時間范圍之內的 ping 都將會被計算在內,包括當前(指 t 時刻)的 ping。
保證每次對 ping 的調用都使用比之前更大的 t 值。
?
示例:
輸入:inputs = ["RecentCounter","ping","ping","ping","ping"], inputs = [[],[1],[100],[3001],[3002]]
輸出:[null,1,2,3,3]
?
提示:
?? ?每個測試用例最多調用 10000 次 ping。
?? ?每個測試用例會使用嚴格遞增的 t 值來調用 ping。
?? ?每次調用 ping 都有 1 <= t <= 10^9。
思路:可以維護一個隊列,只存未過期的即可。官方題解也是這么寫的。
class RecentCounter {Queue<Integer> q=new LinkedList();;public RecentCounter() {}public int ping(int t) {q.add(t);while (q.peek() < t-3000)q.poll();return q.size();} }/*** Your RecentCounter object will be instantiated and called as such:* RecentCounter obj = new RecentCounter();* int param_1 = obj.ping(t);*/但是,可能會面臨一個poll的峰值,影響性能。
目前我想到的方案可以直接弄個數組(如果做限制可以循環數組,但是它要求返回數量,沒辦法)
class RecentCounter {Queue<Integer> q=new LinkedList();int[] arr=new int[10000];int a,b;public RecentCounter() {a=0;b=0;} /*public int ping(int t) {q.add(t);while (q.peek() < t-3000)q.poll();return q.size();}*/public int ping(int t) {arr[b++]=t;while (a<10000 && arr[a] < t-3000)a++;return b-a;}}/*** Your RecentCounter object will be instantiated and called as such:* RecentCounter obj = new RecentCounter();* int param_1 = obj.ping(t);*/?
總結
以上是生活随笔為你收集整理的leetcode933. 最近的请求次数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奶茶妹妹上演京东爱情故事 扑倒大叔10大
- 下一篇: 《F1 2017》图文攻略 赛制、模式与