《零基础Go语言算法实战》【题目 4-8】用 Go 语言设计一个遵循最近最少使用(LRU)缓存约束的数据结构

《零基础Go语言算法实战》

【题目 4-8】用 Go 语言设计一个遵循最近最少使用(LRU)缓存约束的数据结构

实现 LRUCache 类。

● LRUCache(int capacity) :初始化具有正大小容量的 LRU 缓存。

● int get(int key) :如果 key 存在,则返回 key 的值;否则返回 -1。

● void put(int key, int value) :如果键存在,则更新键的值;否则将键值对添加到缓存中。

如果密钥数量超过此操作的容量,则移除 LRU 的密钥。

● get() 和 put() 方法必须分别以 O(1) 的平均时间复杂度运行。

101

零基础

Go语言算法实战

【解答】

① 思路。

根据要求,可以通过双向链表来设计 LRUCache 对象及其 get()、put() 方法。

② Go 语言实现。

package main

import "fmt"

type LRUCache struct {

capacity int

head, tail *Node

values mapint*Node

}

type Node struct {

key, value int

prev, next *Node

}

func Constructor(capacity int) LRUCache {

return LRUCache{

values: mapint*Node{},

capacity: capacity,

}

}

func (lr *LRUCache) Get(key int) int {

node, ok := lr.valueskey

if !ok {

return -1

}

lr.moveToLast(node)

return node.value

}

func (lr *LRUCache) moveToLast(node *Node) {

if node == lr.tail {

return

}

if node == lr.head {

lr.head = lr.head.next

lr.head.prev = nil

} else {

node.prev.next = node.next

node.next.prev = node.prev

}

lr.tail.next = node

node.prev = lr.tail

lr.tail = lr.tail.next

lr.tail.next = nil

}

func (lr *LRUCache) Put(key int, value int) {

if _, ok := lr.valueskey; ok {

lr.valueskey.value = value

lr.moveToLast(lr.valueskey)

return

}

if len(lr.values) < lr.capacity {

lr.append(key, value)

return

}

node := lr.head

lr.moveToLast(node)

delete(lr.values, node.key)

lr.valueskey = node

node.key = key

node.value = value

}

func (lr *LRUCache) append(key, value int) {

node := &Node{

key: key,

value: value,

}

if lr.tail == nil {

lr.tail = node

lr.head = node

} else {

lr.tail.next = node

node.prev = lr.tail

lr.tail = node

}

lr.valueskey = node

}

func main() {

obj := Constructor(2)

obj.Put(5, 88)

res := obj.Get(5)

fmt.Println(res)

}

//$ go run interview4-8.go

//88

相关推荐
BothSavage14 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn14 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
纯爱掌门人15 小时前
干了这么多年前端,聊聊 2026 年我们到底还值不值钱
前端·程序员
AskHarries16 小时前
用 OpenClaw 做一份完整 PPT:从主题、提纲到 slide deck
后端·程序员
齐翊16 小时前
分享一个在 Claude Code 里 [同时] 用多个 ApiKey 的方法
程序员·github·agent
烬羽16 小时前
从"抽卡"到"搭台":一文讲透上下文工程(Context Engineering)的底层逻辑
程序员
烬羽16 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
SimonKing16 小时前
Google第三方授权登录
java·后端·程序员