文章目录

最强解析面试题:Goland 实现LRU算法
文章讲解 “ Goland 实现LRU算法 ” 经典面试题,包含思路及源码,及解惑!
题目
思路
代码
container/list
type entry struct {
K interface{}
V interface{}
}
type lru struct {
s int
l *list.List
m map[interface{}]*list.Element
}
func NewLru(s int) *lru {
return &lru{
s: s,
l: list.New(),
m: make(map[interface{}]*list.Element, s),
}
}
func (l *lru) Get(k interface{}) (interface{}, bool) {
if v, ok := l.m[k]; ok {
l.l.MoveToFront(v)
return v.Value.(*entry).V, true
}
return nil, false
}
func (l *lru) Push(key, value interface{}) {
if v, ok := l.m[key]; ok {
v.Value.(*entry).V = value
l.l.MoveToFront(v)
return
}
if l.l.Len() >= l.s {
last := l.l.Back()
l.l.Remove(last)
}
e := l.l.PushFront(&entry{key, value})
l.m[key] = e
return
}