-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsolution.go
More file actions
86 lines (73 loc) · 1.19 KB
/
solution.go
File metadata and controls
86 lines (73 loc) · 1.19 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
package lru_cache
type Node struct {
Key int
Val int
Prev *Node
Next *Node
}
type LRUCache struct {
Capacity int
Head *Node
Tail *Node
Map map[int]*Node
}
func Constructor(capacity int) LRUCache {
return LRUCache{
Capacity: capacity,
Map: map[int]*Node{},
}
}
func (lc *LRUCache) Get(key int) int {
node, ok := lc.Map[key]
if !ok {
return -1
}
lc.remove(node)
lc.add(node)
return node.Val
}
func (lc *LRUCache) Put(key int, val int) {
node, ok := lc.Map[key]
if ok {
node.Val = val
lc.remove(node)
lc.add(node)
return
}
node = &Node{
Key: key,
Val: val,
}
if lc.Capacity <= len(lc.Map) {
delete(lc.Map, lc.Head.Key)
lc.remove(lc.Head)
}
lc.add(node)
lc.Map[key] = node
return
}
func (lc *LRUCache) remove(node *Node) {
if lc.Head == node && lc.Tail == node {
lc.Head = nil
lc.Tail = nil
return
}
if lc.Head == node {
lc.Head = node.Next
} else if lc.Tail == node {
lc.Tail = node.Prev
} else {
node.Prev.Next = node.Next
node.Next.Prev = node.Prev
}
}
func (lc *LRUCache) add(node *Node) {
if lc.Tail == nil {
lc.Head = node
lc.Tail = node
return
}
node.Prev = lc.Tail
lc.Tail.Next = node
lc.Tail = node
}