362. Design Hit Counter
1. if we need to keep all the historical data
1. if we need to keep all the historical data
use treemap<time, count>
hit: O(logn)
getHits: O(logn)class HitCounter {
TreeMap<Integer, Integer> map;
int count = 0;
public HitCounter() {
map = new TreeMap<>();
}
public void hit(int timestamp) {
count++;
map.put(timestamp, count);
}
public int getHits(int timestamp) {
Integer cur = map.floorKey(timestamp);
int curCount = cur != null ? map.get(cur) : 0;
int start = timestamp - 300;
if (start >= 0) {
Integer before = map.floorKey(start);
return curCount - (before != null ? map.get(before) : 0);
}
return curCount;
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
the past 300 seconds).
timestamp parameter (in seconds granularity),
timestamp is monotonically increasing
Several hits may arrive roughly at the same time.
Records a hit that happened at timestamp (in seconds). Several hits may happen at the same timestamp.
Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).
nput
["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"]
[[], [1], [2], [3], [4], [300], [300], [301]] => time
Output
[null, null, null, null, 3, null, 4, 3]
hits depends on time
1. if we need to keep all the historical data
use treemap<time, count>
2. no need to keep the historical data
but!
All the calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing).
this means getHits(time), the time is incresing, we dont need to look up old data
so the idea is queue, FIFO
*/2. no need to keep the historical data
use queue, FIFO
but for huge data at the same time, queue is easy out of memory
# circular buffer idea
so just maintain two arrays (size 300) to keep data
T:
hit: O(1)
getHits: O(300)
S: O(600)
more comment
Last updated
Was this helpful?