力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
定义LRU结构体
type LRUCache struct {
Cache map[int]*list.Element // 通过 O(1)复杂度查找元素
List *list.List // 保存元素的顺序,访问的元素放在最前面
Capacity int // 缓存容量
}
Element 里面 Value 对应的 值
type Item struct {
Key int // 主要用于查找该元素在 Cache 中的位置,好删除最末尾的元素
Value int // 元素的值
}
初始化 LRUCache
func Constructor(capacity int) LRUCache {
return LRUCache{
Cache: make(map[int]*list.Element),
List: list.New(),
Capacity: capacity,
}
}
Get 方法,访问的元素放在最前面
func (this *LRUCache) Get(key int) int {
if e := this.Cache[key]; e != nil {
this.List.MoveToFront(e)
return e.Value.(*Item).Value
}
return -1
}
Put 方法
func (this *LRUCache) Put(key int, value int) {
if e := this.Cache[key]; e != nil {
// 更新元素
this.List.MoveToFront(e)
e.Value.(*Item).Value = value
} else {
if this.List.Len() < this.Capacity {
// 直接放到头部
element := this.List.PushFront(&Item{key, value})
this.Cache[key] = element
}else {
// 移除尾部元素
back := this.List.Back()
this.List.Remove(back)
delete(this.Cache, back.Value.(*Item).Key)
// 新增头部元素
element := this.List.PushFront(&Item{key, value})
this.Cache[key] = element
}
}
}