-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathlru_cache.ts
35 lines (28 loc) · 898 Bytes
/
lru_cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 146. LRU Cache
// https://leetcode.com/problems/lru-cache/
export default class LRUCache {
constructor(capacity: number) {
this.capacity = capacity;
}
capacity: number;
cache: Map<number, number> = new Map();
get(key: number): number {
if (!this.cache.has(key)) return -1;
const value = this.cache.get(key)!;
// delete and set to move the value to the tail (most recent)
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
put(key: number, value: number): void {
if (this.cache.has(key)) {
// delete to move the value to the tail (most recent)
this.cache.delete(key);
} else if (this.cache.size === this.capacity) {
// delete the head (least recent) value
this.cache.delete(this.cache.keys().next().value);
}
// put the value to the tail (most recent)
this.cache.set(key, value);
}
}