Design hit Counter

Source: Internet
Author: User

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?

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

 Public classHitCounter {PrivateHashmap<integer, integer>map; /**Initialize your data structure here.*/     PublicHitCounter () {map=NewHashmap<integer, integer>(); }        /**Record a hit. @paramtimestamp-the current timestamp (in seconds granularity).*/     Public voidHitinttimestamp) {        if(Map.containskey (timestamp)) {Map.put (Timestamp,map.get (timestamp) )+1); }        Else{map.put (timestamp,1); }            }        /**Return the number of hits in the past 5 minutes. @paramtimestamp-the current timestamp (in seconds granularity).*/     Public intGethits (inttimestamp) {        intBegin = Timestamp-300; intsum = 0;  for(intKey:map.keySet ()) {            if(key>begin&&key<=timestamp) {Sum= Sum +Map.get (key); }        }                returnsum; }}/*** Your HitCounter object would be instantiated and called as such: * hitcounter obj = new HitCounter (); * Obj.hit (Time Stamp); * int param_2 = obj.gethits (timestamp); */

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.