《零基础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

相关推荐
安全系统学习25 分钟前
网络安全逆向分析之rust逆向技巧
前端·算法·安全·web安全·网络安全·中间件
菜鸟懒懒2 小时前
exp1_code
算法
AI大模型2 小时前
大模型系列炼丹术(六) - 别只会用Greedy!6种主流LLM解码策略全面解析,附适用场景
程序员·llm
Winn~2 小时前
JVM垃圾回收器-ZGC
java·jvm·算法
爱coding的橙子3 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光3 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿3 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm3 小时前
leetcode78. 子集
算法·深度优先
岁忧3 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
dying_man3 小时前
LeetCode--18.四数之和
算法·leetcode