Skip to content

Commit b951fda

Browse files
author
baxiang
committed
lru 缓存
1 parent ac6d892 commit b951fda

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Go/leetcode/146lru-cache/main.go

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package main
2+
3+
import "fmt"
4+
5+
type Node struct {
6+
key int
7+
value int
8+
pre *Node
9+
next *Node
10+
}
11+
12+
type LRUCache struct {
13+
m map[int] *Node
14+
head *Node
15+
tail *Node
16+
capacity int
17+
}
18+
19+
20+
func Constructor(capacity int) LRUCache {
21+
cache := LRUCache{
22+
m: make(map[int]*Node),
23+
head: &Node{},
24+
tail: &Node{},
25+
capacity: capacity,
26+
}
27+
cache.head.next = cache.tail
28+
cache.tail.pre = cache.head
29+
return cache
30+
}
31+
// 头部添加元素
32+
func (this *LRUCache)AddHead(n *Node){
33+
tmp := this.head.next
34+
this.head.next = n
35+
n.next = tmp
36+
n.pre = this.head
37+
tmp.pre = n
38+
}
39+
func (this *LRUCache)RemoveNode(n *Node){
40+
pre := n.pre
41+
next := n.next
42+
pre.next = next
43+
next.pre = pre
44+
n.pre = nil
45+
n.next = nil
46+
}
47+
48+
49+
func (this *LRUCache) Get(key int) int {
50+
node ,ok:= this.m[key]
51+
if ok {
52+
this.RemoveNode(node)
53+
this.AddHead(node)
54+
return node.value
55+
}
56+
return -1
57+
}
58+
59+
60+
func (this *LRUCache) Put(key int, value int) {
61+
node ,ok:= this.m[key]
62+
if ok {// 存在
63+
if node.value!= value {
64+
node.value = value
65+
}
66+
this.RemoveNode(node)
67+
this.AddHead(node)
68+
}else {
69+
n := &Node{
70+
key:key,
71+
value: value,
72+
}
73+
if this.capacity==len(this.m) {// 删除
74+
delete(this.m,this.tail.pre.key)
75+
this.RemoveNode(this.tail.pre)
76+
}
77+
this.AddHead(n)
78+
this.m[key] = n
79+
}
80+
}
81+
func main() {
82+
cache := Constructor(2)
83+
cache.Put(1,1)
84+
cache.Put(2,2)
85+
fmt.Println(cache.Get(1))//1
86+
cache.Put(3,3)
87+
fmt.Println(cache.Get(2))//-1
88+
cache.Put(4,4)
89+
fmt.Println(cache.Get(1))//-1
90+
fmt.Println(cache.Get(3))//3
91+
fmt.Println(cache.Get(4))//4
92+
}

0 commit comments

Comments
 (0)