2622.有时间限制的缓存
链接:2622.有时间限制的缓存
难度:Medium
标签:
简介:编写一个类,它允许获取和设置键-值对,并且每个键都有一个 过期时间 。
题解 1 - typescript
- 编辑时间:2023-04-23
- 执行用时:68ms
- 内存消耗:42.6MB
- 编程语言:typescript
- 解法介绍:哈希存储。
class TimeLimitedCache {
    cache = new Map<number, [number, number]>();
    set(key: number, value: number, duration: number): boolean {
        const now = Date.now();
        const item = this.cache.get(key);
        if (item) {
            item[0] = now + duration;
            item[1] = value;
            return true;
        } else {
            this.cache.set(key, [now + duration, value]);
            return false;
        }
    }
    get(key: number): number {
        const now = Date.now();
        const item = this.cache.get(key);
        if (!item || now > item[0]) return -1;
        return item[1];
    }
    count(): number {
        const now = Date.now();
        let res = 0;
        for (const [key, item] of this.cache.entries()) {
            if (now > item[0]) {
                this.cache.delete(key);
            } else {
                res++;
            }
        }
        return res;
    }
}