Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class HitCounter {
- List<Integer> data;
- /** Initialize your data structure here. */
- public HitCounter() {
- data = new ArrayList();
- data.add(Integer.MIN_VALUE);
- data.add(Integer.MAX_VALUE);
- }
- /** Record a hit.
- @param timestamp - The current timestamp (in seconds granularity). */
- public void hit(int timestamp) {
- data.set(data.size() - 1, timestamp);
- data.add(Integer.MAX_VALUE);
- }
- /** Return the number of hits in the past 5 minutes.
- @param timestamp - The current timestamp (in seconds granularity). */
- public int getHits(int timestamp) {
- return getHitsBelow(timestamp + 1) - getHitsBelow(timestamp - 300 + 1);
- }
- private int getHitsBelow(int timestamp) {
- int lo = 0;
- int hi = data.size();
- while(lo < hi) {
- int mid = lo + (hi - lo) / 2;
- if(data.get(mid) < timestamp && data.get(mid + 1) >= timestamp) {
- return mid;
- }
- if(data.get(mid) >= timestamp) {
- hi = mid;
- } else {
- lo = mid + 1;
- }
- }
- return hi;
- }
- }
- /**
- * Your HitCounter object will be instantiated and called as such:
- * HitCounter obj = new HitCounter();
- * obj.hit(timestamp);
- * int param_2 = obj.getHits(timestamp);
- */
Add Comment
Please, Sign In to add comment