// Get 获取键对应的值 func(l *LRUCache) Get(key int) int { if elem, ok := l.cache[key]; ok { // 将访问的元素移动到链表头部表示最近使用 l.list.MoveToFront(elem) return elem.Value.(*entry).value } return-1 }
// Put 插入或更新键值对 func(l *LRUCache) Put(key int, value int) { // 如果键已存在,更新值并移动到头部 if elem, ok := l.cache[key]; ok { l.list.MoveToFront(elem) elem.Value.(*entry).value = value return } // 如果缓存已满,删除最近最少使用的元素(链表尾部) if l.list.Len() == l.capacity { tail := l.list.Back() if tail != nil { delete(l.cache, tail.Value.(*entry).key) l.list.Remove(tail) } } // 添加新元素到链表头部 elem := l.list.PushFront(&entry{key, value}) l.cache[key] = elem }
// 如果key存在于缓存中,则返回关键字的值,否则返回-1 func(this *LRUCache) Get(key int) int { if ele, ok := this.keysMap[key]; ok { this.updateListKey(key) return ele } return-1 }
func(this *LRUCache) Put(key int, value int) { // 关键字存在 则更新值为value // 不存在,则插入value // 如果插入超过数量capacity 则删除最久没有使用的关键字【list] if _, ok := this.keysMap[key]; ok { this.updateListKey(key) this.keysMap[key] = value } else { this.updateListKey(key) this.keysMap[key] = value iflen(this.keysList) > this.capacity { delete(this.keysMap, this.keysList[0]) // 这里删除key 从list队列中获取 this.keysList = this.keysList[1:] } } }
func(this *LRUCache) updateListKey(key int) { for i := 0; i < len(this.keysList); i++ { if key == this.keysList[i] { this.keysList = append(this.keysList[:i], this.keysList[i+1:]...) // 删除该key, 然后放在末尾 break } } this.keysList = append(this.keysList, key) }