-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode-146-LRUCache.js
123 lines (105 loc) · 2.17 KB
/
leetcode-146-LRUCache.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// /**
// * @param {number} capacity
// */
// var LRUCache = function(capacity) {
// };
// /**
// * @param {number} key
// * @return {number}
// */
// LRUCache.prototype.get = function(key) {
// };
// /**
// * @param {number} key
// * @param {number} value
// * @return {void}
// */
// LRUCache.prototype.put = function(key, value) {
// };
// /**
// * 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)
// */
// h t
// a <-> b <-> c
//
class Node {
constructor(key, val) {
this.key = key;
this.val = val;
this.next = null;
this.prev = null;
}
}
class Dll {
constructor() {
this.head = new Node();
this.tail = new Node();
this.head.next = this.tail;
this.tail.prev = this.head;
}
removeNode(node) {
let p = node.prev;
let n = node.next;
p.next = n;
n.prev = p;
}
addTail(node) {
let c = this.tail.prev;
c.next = node;
node.prev = c;
node.next = this.tail;
this.tail.prev = node;
}
moveToTail(node) {
this.removeNode(node);
this.addTail(node);
}
removeHead() {
let c = this.head.next;
this.removeNode(c);
return c.key;
}
}
class LRUCache {
constructor(cap) {
this.cap = cap;
this.size = 0;
this.map = {};
this.dll = new Dll();
}
get(key) {
if (!(key in this.map)) return -1;
this.dll.moveToTail(this.map[key]);
return this.map[key].val;
}
put(key, val) {
// if key not in map:
// addTail(new node)
// set map[key] = node
//
// - if size === cap:
// --- removeHead
// --- remove map[headKey]
// - if size < cap:
// --- size++
//
// if key in map:
// - (map[key].val = val)
// - move node to tail: moveToTail(node)
if (!(key in this.map)) {
const newNode = new Node(key, val);
this.dll.addTail(newNode);
this.map[key] = newNode;
if (this.size === this.cap) {
const c = this.dll.removeHead();
delete this.map[c];
} else this.size++;
} else {
this.map[key].val = val;
this.dll.moveToTail(this.map[key]);
}
}
}