0
点赞
收藏
分享

微信扫一扫

最强解析面试题:Goland 实现LRU算法

文章目录


在这里插入图片描述

最强解析面试题: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
}

附录

举报

相关推荐

0 条评论