-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16.LRUCashe_LinkedList.js
More file actions
98 lines (88 loc) · 2.25 KB
/
16.LRUCashe_LinkedList.js
File metadata and controls
98 lines (88 loc) · 2.25 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class LRUCashe {
constructor(capacity) {
this.capacity = capacity
this.q = []
this.m = {}
}
get(key) {
if (this.m[key]) {
const value = this.m[key].value
this.put(key, value)
return value
}
return -1
}
put(key, value) {
if (this.m[key]) {
this.q.splice(this.q.findIndex(node => node === this.m[key]), 1)
this.m[key] = null
}
this.q.push({key, value})
this.m[key] = this.q[this.q.length - 1]
if (this.q.length > this.capacity) {
this.m[this.q.shift().key] = null
}
}
}
const cash = new LRUCashe(3);
cash.put(2, 1)
cash.put(1, 2)
cash.put(5, 44)
cash.put(0, 1)
cash.put(7, 3)
cash.put(5, 3)
cash.get(5)
cash.get(7)
console.log(cash.q);
// LRU cash 2 версия: со связным списком вместо массива, чтобы за O(1) вставлять
// и получать элементы, а не за линейную сложность
// со splice и find по массиву
class Node {
constructor(key, value) {
this.key = key
this.value = value
this.next = null
this.prev = null
}
}
class LinkedList {
constructor() {
this.length = 0
this.head = this.tail = null
}
push(node) {
if (!this.tail) {
this.tail = this.head = node
}
this.tail.next = node
node.prev = this.tail
this.tail = node
this.length++
}
shift() {
const result = this.tail
this.tail = this.tail.prev
this.tail.next = null
this.length--
return result
}
splice(node) {
let currentNode = this.head
if (!node.prev && !node.next) {
this.head = this.tail = null
} else if (!node.next) {
this.tail.prev.next = null
this.tail = this.tail.prev
} else if (!node.prev) {
this.head = this.head.next
this.head.prev = null
} else {
const prev = node.prev
const next = node.next
prev.next = next
next.prev = prev
node.next = node.prev = null
}
this.length--
}
}