Skip to content

Commit 4d1dac8

Browse files
committed
Add solution #362
1 parent 137a6ae commit 4d1dac8

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,7 @@
350350
359|[Logger Rate Limiter](./solutions/0359-logger-rate-limiter.js)|Easy|
351351
360|[Sort Transformed Array](./solutions/0360-sort-transformed-array.js)|Medium|
352352
361|[Bomb Enemy](./solutions/0361-bomb-enemy.js)|Medium|
353+
362|[Design Hit Counter](./solutions/0362-design-hit-counter.js)|Medium|
353354
363|[Max Sum of Rectangle No Larger Than K](./solutions/0363-max-sum-of-rectangle-no-larger-than-k.js)|Hard|
354355
365|[Water and Jug Problem](./solutions/0365-water-and-jug-problem.js)|Medium|
355356
367|[Valid Perfect Square](./solutions/0367-valid-perfect-square.js)|Easy|

solutions/0362-design-hit-counter.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 362. Design Hit Counter
3+
* https://leetcode.com/problems/design-hit-counter/
4+
* Difficulty: Medium
5+
*
6+
* Design a hit counter which counts the number of hits received in the past 5 minutes
7+
* (i.e., the past 300 seconds).
8+
*
9+
* Your system should accept a timestamp parameter (in seconds granularity), and you may
10+
* assume that calls are being made to the system in chronological order (i.e., timestamp
11+
* is monotonically increasing). Several hits may arrive roughly at the same time.
12+
*
13+
* Implement the HitCounter class:
14+
* - HitCounter() Initializes the object of the hit counter system.
15+
* - void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several
16+
* hits may happen at the same timestamp.
17+
* - int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp
18+
* (i.e., the past 300 seconds).
19+
*/
20+
21+
var HitCounter = function() {
22+
this.hits = [];
23+
};
24+
25+
/**
26+
* @param {number} timestamp
27+
* @return {void}
28+
*/
29+
HitCounter.prototype.hit = function(timestamp) {
30+
this.hits.push(timestamp);
31+
};
32+
33+
/**
34+
* @param {number} timestamp
35+
* @return {number}
36+
*/
37+
HitCounter.prototype.getHits = function(timestamp) {
38+
const threshold = timestamp - 300;
39+
while (this.hits.length && this.hits[0] <= threshold) {
40+
this.hits.shift();
41+
}
42+
return this.hits.length;
43+
};

0 commit comments

Comments
 (0)