关于go:Leetcode专题146LRU-缓存

3次阅读

共计 794 个字符,预计需要花费 2 分钟才能阅读完成。

leetcode 链接:
https://leetcode.cn/problems/lru-cache/
解题思路:

// entry 缓存节点
type entry struct {
    key int
    value int
}

// LRUCache .
type LRUCache struct {
    cap int
    cache map[int]*list.Element
    lst  *list.List
}

// Constructor . 
func Constructor(capacity int) LRUCache {
    return LRUCache{
        cap: capacity,
        cache: map[int]*list.Element{},
        lst: list.New(),}
}

// Get 获取元素
func (this *LRUCache) Get(key int) int {e := this.cache[key]
   if e == nil {return -1}
   this.lst.MoveToFront(e) // 将最近应用的节点置于链表头
   return e.Value.(entry).value
}

// Put 写入元素
func (this *LRUCache) Put(key int, value int)  {
    // 首先判断 key 是否曾经存在
    if e:=this.cache[key]; e != nil {
        // key 存在的状况下,更新值并置于列表头
        e.Value = entry{key, value}
        this.lst.MoveToFront(e)
        return
    }
    // key 不存在的状况下,间接在头节点退出元素
    this.cache[key] = this.lst.PushFront(entry{key, value})
    // 缓存空间满时,淘汰最旧的缓存
    if len(this.cache) > this.cap {delete(this.cache, this.lst.Remove(this.lst.Back()).(entry).key)
    }
}
正文完
 0