forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0146-lru-cache.ts
87 lines (68 loc) · 1.93 KB
/
0146-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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Your LRUCache object will be instantiated and called as such:
* var obj = new LRUCache(capacity)
* var param_1 = obj.get(key)
* obj.put(key,value)
*/
type CacheNode = {
value: number,
key: number | null,
next: CacheNode | null,
prev: CacheNode | null,
};
class LRUCache {
private size: number;
private capacity: number;
private data: Map<number, CacheNode>;
private head: CacheNode;
private tail: CacheNode;
constructor(capacity: number) {
this.capacity = capacity;
this.size = 0;
this.data = new Map();
// Initialize dummy nodes for convenience
this.head = { value: 0 } as CacheNode;
this.tail = { value: 0 } as CacheNode;
this.head.next = this.tail;
this.tail.prev = this.head;
}
get(key: number): number {
const node = this.data.get(key);
if (!node) return -1;
node.prev.next = node.next;
node.next.prev = node.prev;
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
return node.value;
}
put(key: number, value: number): void {
let node = this.data.get(key);
if (!node) {
this.size++;
node = { value, key } as CacheNode;
this.data.set(key, node);
} else {
node.value = value;
node.prev.next = node.next;
node.next.prev = node.prev;
}
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
if (this.size > this.capacity) {
this.evict();
}
}
private evict() {
this.size--;
const node = this.tail.prev;
node.prev.next = node.next;
node.next.prev = node.prev;
node.prev = null;
node.next = null;
this.data.delete(node.key);
}
}