Logger Rate Limiter
Description
null
Solution(javascript)
// /** 1: hash
// * Initialize your data structure here.
// */
// const Logger = function () {
// this.map = {}
// }
// /**
// * Returns true if the message should be printed in the given timestamp, otherwise returns false.
// If this method returns false, the message will not be printed.
// The timestamp is in seconds granularity.
// * @param {number} timestamp
// * @param {string} message
// * @return {boolean}
// */
// Logger.prototype.shouldPrintMessage = function (timestamp, message) {
// if (this.map[message] === undefined || timestamp - this.map[message] >= 10) {
// this.map[message] = timestamp
// return true
// }
// return false
// }
/** 2: 优化空间
* Initialize your data structure here.
*/
const Logger = function () {
this.times = []
this.sets = []
}
/**
* Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity.
* @param {number} timestamp
* @param {string} message
* @return {boolean}
*/
Logger.prototype.shouldPrintMessage = function (timestamp, message) {
const index = timestamp % 10
if (timestamp !== this.times[index]) {
this.times[index] = timestamp
this.sets[index] = {}
}
for (let i = 0; i < this.times.length; i++) {
const time = this.times[i]
if (timestamp - time < 10 && this.sets[i][message]) {
return false
}
}
this.sets[index][message] = true
return true
}