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) }}