Try   HackMD

2622. Cache With Time Limit

tags: leetcode 30 days js challenge Medium

2622. Cache With Time Limit

題目描述

Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.

The class has three public methods:

set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists.

get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1.

count(): returns the count of un-expired keys.

範例

Example 1:

Input: 
["TimeLimitedCache", "set", "get", "count", "get"]
[[], [1, 42, 100], [1], [], [1]]
[0, 0, 50, 50, 150]
Output: [null, false, 42, 1, -1]
Explanation:
At t=0, the cache is constructed.
At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned.
At t=50, key=1 is requested and the value of 42 is returned.
At t=50, count() is called and there is one active key in the cache.
At t=100, key=1 expires.
At t=150, get(1) is called but -1 is returned because the cache is empty.

Example 2:

Input: 
["TimeLimitedCache", "set", "set", "get", "get", "get", "count"]
[[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []]
[0, 0, 40, 50, 120, 200, 250]
Output: [null, false, true, 50, 50, -1]
Explanation:
At t=0, the cache is constructed.
At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned.
At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten.
At t=50, get(1) is called which returned 50.
At t=120, get(1) is called which returned 50.
At t=140, key=1 expires.
At t=200, get(1) is called but the cache is empty so -1 is returned.
At t=250, count() returns 0 because the cache is empty.

Constraints:

  • 0 <= key <= 109
  • 0 <= value <= 109
  • 0 <= duration <= 1000
  • total method calls will not exceed 100

解答

TypeScript

class TimeLimitedCache { private cache: { [key: number]: { value: number; expiredTime: number; }; }; constructor() { this.cache = {}; } set(key: number, value: number, duration: number): boolean { const currentTime = Date.now(); const existed = this.cache[key] ? this.cache[key].expiredTime > currentTime : false; this.cache[key] = { value, expiredTime: Date.now() + duration, }; return existed; } get(key: number): number { const currentTime = Date.now(); if (this.cache[key]?.expiredTime > currentTime) { return this.cache[key].value; } return -1; } count(): number { const currentTime = Date.now(); let counts = 0; for (const value of Object.values(this.cache)) { if (value.expiredTime - currentTime > 0) { counts++; } } return counts; } }

setTimeout + clearTimeout 寫法:

class TimeLimitedCache { cache = new Map<number, { value: number; timeout: NodeJS.Timeout }>(); set(key: number, value: number, duration: number) { const valueInCache = this.cache.get(key); if (valueInCache) { clearTimeout(valueInCache.timeout); } const timeout = setTimeout(() => this.cache.delete(key), duration); this.cache.set(key, { value, timeout }); return Boolean(valueInCache); } get(key: number) { return this.cache.has(key) ? this.cache.get(key)?.value : -1; } count() { return this.cache.size; } }

Priority Queue

import { MinPriorityQueue } from '@datastructures-js/priority-queue'; type Entry = { key: number; value: number; expiration: number; overwritten: boolean; }; class TimeLimitedCache { cache: Record<string, Entry> = {}; queue = new MinPriorityQueue<Entry>(); size = 0; handleExpiredData() { const now = Date.now(); while (this.queue.size() > 0 && this.queue.front().expiration < now) { const entry = this.queue.dequeue(); if (!entry.overwritten) { delete this.cache[entry.key]; this.size -= 1; } } } set(key: number, value: number, duration: number) { this.handleExpiredData(); const hasVal = key in this.cache; if (hasVal) { this.cache[key].overwritten = true; } else { this.size += 1; } const expiration = Date.now() + duration; const entry: Entry = { key, value, expiration, overwritten: false }; this.cache[key] = entry; this.queue.enqueue(entry); return hasVal; } get(key: number) { this.handleExpiredData(); if (this.cache[key] === undefined) return -1; return this.cache[key].value; } count() { this.handleExpiredData(); return this.size; } }

SheepThur, May 18, 2023

Reference

回到題目列表