原題鏈接:
https://leetcode.cn/problems/design-authentication-manager/
理解題意:
-
timeToLive
為token
的有效時間長度 -
currentTime + timeToLive
為token
的到期時間 - 如果當(dāng)前時間超過了緩存的到期時間庐椒,即為過期
解題思路:
- 使用
Map
緩存token
及其到期時間 - 執(zhí)行
generate
時椒舵,將token
和到期時間currentTime + timeToLive
緩存 - 執(zhí)行
renew
時,查看token
的到期時間是否超過了當(dāng)前時間约谈,未超過表示還未過期笔宿,為token
設(shè)置新的到期時間 - 執(zhí)行
countUnexpiredTokens
時,統(tǒng)計Map
中緩存的token
到期時間大于當(dāng)前時間棱诱,即未過期的token
數(shù)量
/**
* @param {number} timeToLive
*/
var AuthenticationManager = function(timeToLive) {
this.timeToLive = timeToLive // 有效時間
this.map = new Map() // 緩存token和過期時間
};
/**
* @param {string} tokenId
* @param {number} currentTime
* @return {void}
*/
AuthenticationManager.prototype.generate = function(tokenId, currentTime) {
// 每次創(chuàng)建時泼橘,保存tokenId和過期時間
// 過期時間為當(dāng)前時間加上有效時間
this.map.set(tokenId, currentTime + this.timeToLive)
};
/**
* @param {string} tokenId
* @param {number} currentTime
* @return {void}
*/
AuthenticationManager.prototype.renew = function(tokenId, currentTime) {
// 如果當(dāng)前token還未到過期時間,就設(shè)置新過期時間為當(dāng)前時間加上有效時間
if (this.map.get(tokenId) > currentTime) {
this.map.set(tokenId, currentTime + this.timeToLive)
}
};
/**
* @param {number} currentTime
* @return {number}
*/
AuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {
let count = 0 // 存儲未過期驗證碼數(shù)量
// 遍歷所有過期時間
for (const time of this.map.values()) {
// 如果當(dāng)前時間還未到過期時間迈勋,就進(jìn)行計數(shù)
if (time > currentTime) {
count++
}
}
return count
};
/**
* Your AuthenticationManager object will be instantiated and called as such:
* var obj = new AuthenticationManager(timeToLive)
* obj.generate(tokenId,currentTime)
* obj.renew(tokenId,currentTime)
* var param_3 = obj.countUnexpiredTokens(currentTime)
*/