Skip to content

Commit 2443052

Browse files
committed
https://leetcode.cn/problems/cache-with-time-limit/
1 parent 78cf47b commit 2443052

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Step 2. Add the dependency
4949

5050
<summary>展开查看</summary>
5151

52+
https://leetcode.cn/problems/cache-with-time-limit/
53+
5254
https://leetcode.cn/problems/sleep
5355

5456
https://leetcode.cn/problems/array-prototype-last

cache-with-time-limit/index.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
export default class TimeLimitedCache {
2+
#map: Map<number, { expires: number; value: number }>;
3+
constructor() {
4+
this.#map = new Map();
5+
}
6+
7+
set(key: number, value: number, duration: number): boolean {
8+
const deadline = Date.now();
9+
const live = (this.#map.get(key)?.expires ?? 0) > deadline;
10+
11+
this.#map.set(key, { value, expires: deadline + duration });
12+
return live;
13+
}
14+
15+
get(key: number): number {
16+
const deadline = Date.now();
17+
const live = (this.#map.get(key)?.expires ?? 0) > deadline;
18+
return (live ? this.#map.get(key)?.value : -1) ?? -1;
19+
}
20+
21+
count(): number {
22+
const deadline = Date.now();
23+
for (const [key, { expires }] of this.#map) {
24+
const live = expires > deadline;
25+
26+
if (!live) this.#map.delete(key);
27+
}
28+
return this.#map.size;
29+
}
30+
}
31+
32+
/**
33+
* Your TimeLimitedCache object will be instantiated and called as such:
34+
* var obj = new TimeLimitedCache()
35+
* obj.set(1, 42, 1000); // false
36+
* obj.get(1) // 42
37+
* obj.count() // 1
38+
*/

0 commit comments

Comments
 (0)