上次编辑到这里,代码来自缓存 点击恢复默认模板
var TimeLimitedCache = function() {
};
/**
* @param {number} key
* @param {number} value
* @param {number} time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
TimeLimitedCache.prototype.set = function(key, value, duration) {
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function(key) {
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function() {
};
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/
javascript 解法, 执行用时: 60 ms, 内存消耗: 41.1 MB, 提交时间: 2023-04-17 15:46:38
var TimeLimitedCache = function() {
this.map = new Map();
};
/**
* @param {number} key
* @param {number} value
* @param {number} time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
TimeLimitedCache.prototype.set = function(key, value, duration) {
this._expire();
const res = this.map.has(key);
const now = Date.now()
this.map.set(key, [value, now + duration]);
return res;
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function(key) {
this._expire();
if ( !this.map.has(key)) return -1;
return this.map.get(key)[0];
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function() {
this._expire();
return this.map.size;
};
TimeLimitedCache.prototype._expire = function() {
const now = Date.now();
this.map.forEach((value, key) => {
if (value[1] <= now) this.map.delete(key);
});
};
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/
typescript 解法, 执行用时: 64 ms, 内存消耗: 42.5 MB, 提交时间: 2023-04-17 15:35:55
class TimeLimitedCache {
private readonly _cache: Map<number, [value: number, expired: number]> = new Map()
set(key: number, value: number, duration: number): boolean {
this._expire()
const res = this._cache.has(key)
const now = Date.now()
this._cache.set(key, [value, now + duration])
return res
}
get(key: number): number {
this._expire()
if (!this._cache.has(key)) return -1
return this._cache.get(key)![0]
}
count(): number {
this._expire()
return this._cache.size
}
private _expire(): void {
const now = Date.now()
this._cache.forEach((value, key) => {
if (value[1] <= now) this._cache.delete(key)
})
}
}
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/