Leetcode Design hit Counter

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.