The original title link is here: https://leetcode.com/problems/design-hit-counter/,
Topic:
Design a hit counter which counts the number of hits received in the past 5 minutes.
Each function accepts a timestamp parameter (in seconds granularity) and your may assume that calls is being made to the S Ystem in chronological order (ie, the timestamp is monotonically increasing). Assume the earliest timestamp starts at 1.
It is possible this several hits arrive roughly at the same time.
Example:
Follow up:
What if the number of hits per second could is very large? Does your design scale?
Exercises
Similar logger rate limiter
Maintain a queue and add new timestamp to the queue every time.
Need to Gethits when the queue header 5min before all poll out and return to Queue.size ().
Time Complexity:hit O (1), Gethits O (queue.size ()).
Space:queue.size ().
AC Java:
1 Public classHitCounter {2 3 /**Initialize your data structure here.*/4Linkedlist<integer>que;5 PublicHitCounter () {6que =NewLinkedlist<integer>();7 }8 9 /**Record a hit.Ten @paramtimestamp-the current timestamp (in seconds granularity).*/ One Public voidHitinttimestamp) { A Que.add (timestamp); - } - the /**Return the number of hits in the past 5 minutes. - @paramtimestamp-the current timestamp (in seconds granularity).*/ - Public intGethits (inttimestamp) { - while(!que.isempty () && Timestamp-que.peek () >= 300){ + Que.poll (); - } + returnque.size (); A } at } - - /** - * Your HitCounter object would be instantiated and called as such: - * HitCounter obj = new HitCounter (); - * Obj.hit (timestamp); in * int param_2 = obj.gethits (timestamp); - */
Leetcode Design hit Counter