-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU_cache.go
43 lines (37 loc) · 932 Bytes
/
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
type LRUCache struct {
m map[int]*list.Element
list *list.List
capacity int
}
type KeyValue struct {
key int
value int
}
func NewLRUCache (capacity int) LRUCache {
var cache LRUCache
cache.capacity = capacity
cache.m = make(map[int]*list.Element)
cache.list = list.New()
return cache
}
func (lru *LRUCache) Get(key int) int {
if e, ok := lru.m[key]; ok {
lru.list.MoveToFront(e)
return e.Value.(*KeyValue).value
}
return -1
}
func (lru *LRUCache) Put(key, value int) {
if e, ok := lru.m[key]; ok {
lru.list.MoveToFront(e)
e.Value = &KeyValue{key, value}
} else {
if lru.list.Len() == lru.capacity {
e := lru.list.Back()
delete(lru.m, e.Value.(*KeyValue).key)
lru.list.Remove(e)
}
lru.list.PushFront(&KeyValue{key, value})
lru.m[key] = lru.list.Front()
}
}