题目链接:
思路:
构建一个 map ,并利用 setTimeout 思想,到了对应的 duration 后 去删除对应 map 的 key 对应的值,我们存入 map 里面的值 包含 value 本身 和 setTimeout 返回的 一个数字
这里需要注意 我本身是采用 中括号形式去访问对象,但是leetcode 不能采用这种方式,大家老老实实采用 . 访问吧
代码:
javascript
var TimeLimitedCache = function () {
this.cache = new Map()
};
/**
* @param {number} key
* @param {number} value
* @param {number} duration time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
TimeLimitedCache.prototype.set = function (key, value, duration) {
const valueInCache = this.cache.get(key)
if (valueInCache) {
clearTimeout(valueInCache.timeout)
}
let timeout = setTimeout(() => this.cache.delete(key), duration)
this.cache.set(key, { value, timeout })
return Boolean(valueInCache)
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function (key) {
if (this.cache.has(key)) return this.cache.get(key).value
else return -1
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function () {
return this.cache.size
};
/**
* const timeLimitedCache = new TimeLimitedCache()
* timeLimitedCache.set(1, 42, 1000); // false
* timeLimitedCache.get(1) // 42
* timeLimitedCache.count() // 1
*/