-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru-cache.go
80 lines (64 loc) · 1.33 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
type LRUCache struct {
Head *Node
Tail *Node
Cap int
NodeMap map[int]*Node
}
type Node struct {
Key int
Val int
Prev *Node
Next *Node
}
func Constructor(capacity int) LRUCache {
head := new(Node)
tail := new(Node)
head.Next = tail
tail.Prev = head
return LRUCache{head, tail, capacity, make(map[int]*Node)}
}
func (this *LRUCache) Get(key int) int {
res := -1
if node, ok := this.NodeMap[key]; ok {
res = node.Val
this.Remove(node)
this.Add(node)
}
return res
}
func (this *LRUCache) Put(key int, value int) {
if node, ok := this.NodeMap[key]; ok {
node.Val = value
this.Remove(node)
this.Add(node)
} else {
if len(this.NodeMap) == this.Cap {
delete(this.NodeMap, this.Tail.Prev.Key)
this.Remove(this.Tail.Prev)
}
newNode := new(Node)
newNode.Key = key
newNode.Val = value
this.NodeMap[key] = newNode
this.Add(newNode)
}
}
func (this *LRUCache) Remove(node *Node) {
nextNode := node.Next
prevNode := node.Prev
nextNode.Prev = prevNode
prevNode.Next = nextNode
}
func (this *LRUCache) Add(node *Node) {
headNext := this.Head.Next
this.Head.Next = node
node.Prev = this.Head
node.Next = headNext
headNext.Prev = node
}
/**
* Your LRUCache object will be instantiated and called as such:
* obj := Constructor(capacity);
* param_1 := obj.Get(key);
* obj.Put(key,value);
*/