《零基础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 map[int]*Node

}

type Node struct {

key, value int

prev, next *Node

}

func Constructor(capacity int) LRUCache {

return LRUCache{

values: map[int]*Node{},

capacity: capacity,

}

}

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

node, ok := lr.values[key]

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.values[key]; ok {

lr.values[key].value = value

lr.moveToLast(lr.values[key])

return

}

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

lr.append(key, value)

return

}

node := lr.head

lr.moveToLast(node)

delete(lr.values, node.key)

lr.values[key] = 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.values[key] = node

}

func main() {

obj := Constructor(2)

obj.Put(5, 88)

res := obj.Get(5)

fmt.Println(res)

}

//$ go run interview4-8.go

//88

相关推荐
tankeven8 分钟前
动态规划专题(03):区间动态规划从原理到实践(未完待续)
c++·算法·动态规划
田梓燊1 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
斯内科1 小时前
FFT快速傅里叶变换
算法·fft
2301_822703201 小时前
开源鸿蒙跨平台Flutter开发:幼儿疫苗全生命周期追踪系统:基于 Flutter 的免疫接种档案与状态机设计
算法·flutter·华为·开源·harmonyos·鸿蒙
贵慜_Derek1 小时前
Managed Agents 里,Harness 到底升级了什么?
人工智能·算法·架构
2301_822703202 小时前
鸿蒙flutter三方库实战——教育与学习平台:Flutter Markdown
学习·算法·flutter·华为·harmonyos·鸿蒙
Jia ming2 小时前
C语言实现日期天数计算
c语言·开发语言·算法
无限进步_3 小时前
【C++&string】大数相乘算法详解:从字符串加法到乘法实现
java·开发语言·c++·git·算法·github·visual studio
苏纪云3 小时前
蓝桥杯考前突击
c++·算法·蓝桥杯
W23035765733 小时前
经典算法详解:最长公共子序列 (LCS) —— 从暴力递归到动态规划完整实现
算法·动态规划·最长子序列