- 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
typeLRUCachestruct {
capacityint
hashmap[int]*DListNode
Head*DListNode
Tail*DListNode
}
funcConstructor(capacityint) *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,
}
returncache
}
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 {
returnlen(lru.hash)
}
func (lru*LRUCache) Cap() int {
returnlru.capacity
}
func (lru*LRUCache) Get(keyint) int {
ifv, ok:=lru.hash[key]; ok {
lru.remove(v)
lru.insert(v)
returnv.Val
}
return-1
}
func (lru*LRUCache) Put(key, valint) {
ifv, ok:=lru.hash[key]; ok {
lru.remove(v)
lru.insert(v)
v.Val=val
} else {
iflru.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)
}
}