-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path146.LRUCache.go
74 lines (65 loc) · 1.26 KB
/
146.LRUCache.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
package linkedList
type LRUCache struct {
capacity int
hash map[int]*DListNode
Head *DListNode
Tail *DListNode
}
func Constructor(capacity int) *LRUCache {
head := &DListNode{Key: -1, Val: -1}
tail := &DListNode{Key: -1, Val: -1}
head.Next = tail
tail.Prev = head
cache := &LRUCache{
capacity: capacity,
hash: make(map[int]*DListNode, capacity),
Head: head,
Tail: tail,
}
return cache
}
func (lru *LRUCache) insert(node *DListNode) {
t := lru.Tail
node.Prev = t.Prev
t.Prev.Next = node
node.Next = t
t.Prev = node
}
func (lru *LRUCache) remove(node *DListNode) {
node.Prev.Next = node.Next
node.Next.Prev = node.Prev
}
func (lru *LRUCache) Len() int {
return len(lru.hash)
}
func (lru *LRUCache) Cap() int {
return lru.capacity
}
func (lru *LRUCache) Get(key int) int {
if v, ok := lru.hash[key]; ok {
lru.remove(v)
lru.insert(v)
return v.Val
}
return -1
}
func (lru *LRUCache) Put(key, val int) {
if v, ok := lru.hash[key]; ok {
lru.remove(v)
lru.insert(v)
v.Val = val
} else {
if lru.Len() == lru.Cap() {
h := lru.Head.Next
lru.remove(h)
// Import! update lru.hash
delete(lru.hash, h.Key)
}
node := &DListNode{
Key: key,
Val: val,
}
lru.hash[key] = node
lru.insert(node)
}
}