forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_362.java
43 lines (38 loc) · 1.3 KB
/
_362.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.fishercoder.solutions;
public class _362 {
public static class Solution1 {
public static class HitCounter {
/**
* Reference: https://discuss.leetcode.com/topic/48758/super-easy-design-o-1-hit-o-s-gethits-no-fancy-data-structure-is-needed,
* I added one more field k to make it more generic.
* It basically maintains a window of size 300, use modular to update the index.
*/
private int[] times;
private int[] hits;
private int k;
public HitCounter() {
k = 300;
times = new int[k];
hits = new int[k];
}
public void hit(int timestamp) {
int index = timestamp % k;
if (times[index] != timestamp) {
times[index] = timestamp;
hits[index] = 1;
} else {
hits[index]++;
}
}
public int getHits(int timestamp) {
int total = 0;
for (int i = 0; i < k; i++) {
if (timestamp - times[i] < k) {
total += hits[i];
}
}
return total;
}
}
}
}