Guest User

Untitled

a guest
Nov 4th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. public class HitCounter {
  2.     List<Integer> data;
  3.     /** Initialize your data structure here. */
  4.     public HitCounter() {
  5.         data = new ArrayList();
  6.         data.add(Integer.MIN_VALUE);
  7.         data.add(Integer.MAX_VALUE);
  8.     }
  9.    
  10.     /** Record a hit.
  11.         @param timestamp - The current timestamp (in seconds granularity). */
  12.     public void hit(int timestamp) {
  13.         data.set(data.size() - 1, timestamp);
  14.         data.add(Integer.MAX_VALUE);
  15.     }
  16.    
  17.     /** Return the number of hits in the past 5 minutes.
  18.         @param timestamp - The current timestamp (in seconds granularity). */
  19.     public int getHits(int timestamp) {
  20.         return getHitsBelow(timestamp + 1) - getHitsBelow(timestamp - 300 + 1);
  21.     }
  22.    
  23.     private int getHitsBelow(int timestamp) {
  24.         int lo = 0;
  25.         int hi = data.size();
  26.         while(lo < hi) {
  27.             int mid = lo + (hi - lo) / 2;
  28.             if(data.get(mid) < timestamp && data.get(mid + 1) >= timestamp) {
  29.                 return mid;
  30.             }
  31.             if(data.get(mid) >= timestamp) {
  32.                 hi = mid;
  33.             } else {
  34.                 lo = mid + 1;
  35.             }
  36.         }
  37.         return hi;
  38.     }
  39. }
  40.  
  41. /**
  42.  * Your HitCounter object will be instantiated and called as such:
  43.  * HitCounter obj = new HitCounter();
  44.  * obj.hit(timestamp);
  45.  * int param_2 = obj.getHits(timestamp);
  46.  */
Add Comment
Please, Sign In to add comment