-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathlru_cache.go
More file actions
45 lines (38 loc) · 809 Bytes
/
lru_cache.go
File metadata and controls
45 lines (38 loc) · 809 Bytes
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
package leetcode
import "container/list"
//实现Lru缓存
type LRUCache struct {
m map[int]*list.Element
lis *list.List
capacity int
}
type Node struct {
Key, Value int
}
func Constructor(capacity int) LRUCache {
return LRUCache{
make(map[int]*list.Element, capacity),
list.New(),
capacity,
}
}
func (this *LRUCache) Get(key int) int {
if e, ok := this.m[key]; ok {
this.lis.MoveToFront(e)
return e.Value.(Node).Value
}
return -1
}
func (this *LRUCache) Put(key int, value int) {
if e, ok := this.m[key]; ok {
e.Value = Node{key, value}
this.lis.MoveToFront(e)
} else {
if this.lis.Len() == this.capacity {
last := this.lis.Back()
this.lis.Remove(last)
delete(this.m, last.Value.(Node).Key)
}
this.m[key] = this.lis.PushFront(Node{key, value})
}
}