-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru_cache.go
87 lines (80 loc) · 1.76 KB
/
lru_cache.go
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
package design
type LRUCache struct {
capacity int
size int
entries map[int]*Entry
head *Entry
tail *Entry
}
func Constructor(capacity int) LRUCache {
return LRUCache{
capacity: capacity,
size: 0,
entries: make(map[int]*Entry),
head: nil,
tail: nil,
}
}
func (this *LRUCache) Get(key int) int {
// If the key is already in the cache
if entry, exists := this.entries[key]; exists {
// Delete entry from the current position and move to head
this.deleteEntry(entry)
this.updateHead(entry)
return entry.value
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
// If the key already exists in the cache
if entry, exists := this.entries[key]; exists {
entry.value = value
this.deleteEntry(entry)
this.updateHead(entry)
} else {
// Create new node
entry := &Entry{key: key, value: value}
if this.size >= this.capacity {
delete(this.entries, this.tail.key)
this.deleteEntry(this.tail)
this.size--
}
// Update head
this.updateHead(entry)
this.entries[key] = entry
this.size++
}
}
func (this *LRUCache) deleteEntry(entry *Entry) {
// If the given entry is not the head
if entry.previous != nil {
entry.previous.next = entry.next
} else {
this.head = entry.next
}
// If the given entry is not the tail
if entry.next != nil {
entry.next.previous = entry.previous
} else {
this.tail = entry.previous
}
}
func (this *LRUCache) updateHead(entry *Entry) {
// Make entry as the new head
entry.next = this.head
entry.previous = nil
// If head is not null
if this.head != nil {
this.head.previous = entry
}
// Update the head
this.head = entry
// If there's only single node
if this.tail == nil {
this.tail = entry
}
}
type Entry struct {
key, value int
previous, next *Entry
}