-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0146-lru-cache.js
More file actions
74 lines (59 loc) · 1.68 KB
/
0146-lru-cache.js
File metadata and controls
74 lines (59 loc) · 1.68 KB
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
/**
* https://leetcode.com/problems/lru-cache/
* Time O(1) | Space O(N)
* 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)
*/
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.map = new Map();
this.head = {};
this.tail = {};
this.head.next = this.tail;
this.tail.prev = this.head;
}
removeLastUsed() {
const [key, next, prev] = [
this.head.next.key,
this.head.next.next,
this.head,
];
this.map.delete(key);
this.head.next = next;
this.head.next.prev = prev;
}
put(key, value) {
const hasKey = this.get(key) !== -1;
const isAtCapacity = this.map.size === this.capacity;
if (hasKey) return (this.tail.prev.value = value);
if (isAtCapacity) this.removeLastUsed();
const node = { key, value };
this.map.set(key, node);
this.moveToFront(node);
}
moveToFront(node) {
const [prev, next] = [this.tail.prev, this.tail];
this.tail.prev.next = node;
this.connectNode(node, { prev, next });
this.tail.prev = node;
}
connectNode(node, top) {
node.prev = top.prev;
node.next = top.next;
}
get(key) {
const hasKey = this.map.has(key);
if (!hasKey) return -1;
const node = this.map.get(key);
this.disconnectNode(node);
this.moveToFront(node);
return node.value;
}
disconnectNode(node) {
node.next.prev = node.prev;
node.prev.next = node.next;
}
}