forked from jsjtzyy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC362_DesignHitCounter.java
More file actions
50 lines (46 loc) · 1.4 KB
/
LC362_DesignHitCounter.java
File metadata and controls
50 lines (46 loc) · 1.4 KB
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
44
45
46
47
48
49
50
import java.util.*;
public class LC362_DesignHitCounter {
HashMap<Integer, Integer> map;
PriorityQueue<Integer> pq;
int count;
/** Initialize your data structure here. */
public LC362_DesignHitCounter() {
map = new HashMap<>();
pq = new PriorityQueue<>();
count = 0;
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
public void hit(int timestamp) {
count++;
if(map.containsKey(timestamp)){
map.put(timestamp, map.get(timestamp) + 1);
}else{
map.put(timestamp, 1);
pq.add(timestamp);
}
int val = 0;
while(!pq.isEmpty() && pq.peek() <= timestamp - 300){
val = pq.poll();
count -= map.get(val);
map.remove(val);
}
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
public int getHits(int timestamp) {
int val = 0;
while(!pq.isEmpty() && pq.peek() <= timestamp - 300){
val = pq.poll();
count -= map.get(val);
map.remove(val);
}
return count;
}
}
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/