LRU (Least Recently Used) 最近最少使用算法
实现思路:k,v存储形式,数据结构为map+双向链表
map中key对应的value指向链表上的某个节点
插入新值时,将新值组装成节点放在链表头部,并将key加入map,value指向链表头部节点
当获取一个已经存在的值时,将存储该值的链表节点移到链表头部
当插入的值的数量达到预设的上限时,移除链表尾部的节点,移除map中对应的key
package main
import (
"container/list"
"fmt"
)
type LRUCache[K comparable, V any] struct {
cap int
cache map[K]*list.Element
list *list.List
}
type entity[K comparable, V any] struct {
key K
value V
}
func New[K comparable, V any](cap int) LRUCache[K, V] {
return LRUCache[K, V]{
cap: cap,
list: list.New(),
cache: make(map[K]*list.Element),
}
}
func (l *LRUCache[K, V]) Get(key K) (V, bool) {
if elem, ok := l.cache[key]; ok {
l.list.MoveToFront(elem)
return elem.Value.(entity[K, V]).value, true
}
return *new(V), false
}
func (l *LRUCache[K, V]) Set(key K, value V) {
if elem, ok := l.cache[key]; ok {
l.list.MoveToFront(elem)
elem.Value = entity[K, V]{key, value}
} else {
if l.list.Len() >= l.cap {
delete(l.cache, l.list.Back().Value.(entity[K, V]).key)
l.list.Remove(l.list.Back())
}
l.list.PushFront(entity[K, V]{key, value})
l.cache[key] = l.list.Front()
}
}
func main() {
l := New[string, int](3)
l.Set("a", 1)
l.Set("b", 2)
l.Set("c", 3)
l.Set("d", 4)
fmt.Println(l.Get("c"))
fmt.Println(l.Get("d"))
fmt.Println(l.Get("b"))
fmt.Println(l.Get("a"))
}