Sunday, February 3, 2019
362. Design Hit Counter
Version #1 Circular Array
69.23 %
class HitCounter {
int[] time;
int[] count;
/** Initialize your data structure here. */
public HitCounter() {
// time index = timestamp % 300, we can override the previous value since it has expired
time = new int[300];
count = new int[300];
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
int index = timestamp % 300;
if (time[index] != timestamp) {
time[index] = timestamp;
count[index] = 1;
} else {
count[index]++;
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
public int getHits(int timestamp) {
int result = 0;
for (int i = 0; i < 300; i++) {
if (time[i] + 300 > timestamp) {
result += count[i];
}
}
return result;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment