forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
design-hit-counter.cpp
45 lines (38 loc) · 1.13 KB
/
design-hit-counter.cpp
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
// Time: O(1), amortized
// Space: O(k), k is the count of seconds.
class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() : count_(0) {
}
/** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
getHits(timestamp);
if (!dq_.empty() && dq_.back().first == timestamp) {
++dq_.back().second;
} else {
dq_.emplace_back(timestamp, 1);
}
++count_;
}
/** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
while (!dq_.empty() && dq_.front().first <= timestamp - k_) {
count_ -= dq_.front().second;
dq_.pop_front();
}
return count_;
}
private:
const int k_ = 300;
int count_;
deque<pair<int, int>> dq_;
};
/**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/