Design Hit Counter
Description
null
Solution(javascript)
// /**
// * Initialize your data structure here.
// */
// const HitCounter = function () {
// this.map = {}
// }
// /**
// * Record a hit.
// @param timestamp - The current timestamp (in seconds granularity).
// * @param {number} timestamp
// * @return {void}
// */
// HitCounter.prototype.hit = function (timestamp) {
// this.map[timestamp] = (this.map[timestamp] || 0) + 1
// }
// /**
// * Return the number of hits in the past 5 minutes.
// @param timestamp - The current timestamp (in seconds granularity).
// * @param {number} timestamp
// * @return {number}
// */
// HitCounter.prototype.getHits = function (timestamp) {
// let count = 0
// for (let i = timestamp; i > timestamp - 300; i--) {
// if (this.map[i] >= 1) {
// count += this.map[i]
// }
// }
// return count
// }
/**
* Initialize your data structure here.
*/
const HitCounter = function () {
this.indices = []
this.counts = []
}
/**
* Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
* @param {number} timestamp
* @return {void}
*/
HitCounter.prototype.hit = function (timestamp) {
const index = timestamp % 300
if (timestamp !== this.indices[index]) {
this.indices[index] = timestamp
this.counts[index] = 1
} else {
this.counts[index] += 1
}
}
/**
* Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
* @param {number} timestamp
* @return {number}
*/
HitCounter.prototype.getHits = function (timestamp) {
let count = 0
for (let i = 0; i < 300; i++) {
if (timestamp - this.indices[i] < 300) {
count += this.counts[i]
}
}
return count
}