go语言实现LRU缓存

go语言实现LRU Cache

题目描述

设计和构建一个"最近最少使用"缓存,该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值),并在初始化时指定最大容量。当缓存被填满时,它应该删除最近最少使用的项目。

它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。

写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

详细代码

go 复制代码
type LRUCache struct {
	capacity   int
	m          map[int]*Node
	head, tail *Node
}

type Node struct {
	Key       int
	Value     int
	Pre, Next *Node
}

func Constructor(capacity int) LRUCache {
	head, tail := &Node{}, &Node{}
	head.Next = tail
	tail.Pre = head
	return LRUCache{
		capacity: capacity,
		m:        map[int]*Node{},
		head:     head,
		tail:     tail,
	}
}

func (this *LRUCache) Get(key int) int {
	// 存在,放到头
	if v, ok := this.m[key]; ok {
		this.moveToHead(v)
		return v.Value
	}
	// 不存在,返回-1
	return -1
}

func (this *LRUCache) Put(key int, value int) {
	// 已经存在了
	if v, ok := this.m[key];ok{
		v.Value = value
		this.moveToHead(v)
		return 
	}
	if this.capacity==len(this.m){
		rmKey := this.removeTail()
		delete(this.m ,rmKey)
	}
	newNode := &Node{Key: key, Value: value}
	this.m[key] = newNode
	this.addToHead(newNode)
}

func (this *LRUCache) moveToHead(node *Node) {
	this.deleteNode(node)
	this.addToHead(node)
}

func (this *LRUCache) deleteNode(node *Node) {
	node.Pre.Next = node.Next
	node.Next.Pre = node.Pre
}

func (this *LRUCache) addToHead(node *Node) {
	// 先让node位于现存第一位元素之前
	this.head.Next.Pre = node
	// 通过node的next指针让原始第一位元素放到第二位
	node.Next = this.head.Next
	// 捆绑node和head的关系
	this.head.Next = node
	node.Pre = this.head
}

func (this *LRUCache)removeTail()int{
	node := this.tail.Pre
    this.deleteNode(node)
    return node.Key
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * obj := Constructor(capacity);
 * param_1 := obj.Get(key);
 * obj.Put(key,value);
 */
相关推荐
福大大架构师每日一题3 小时前
ollama v0.30.7 正式发布:Hermes 桌面端落地,接口、文档、底层依赖全方位优化
golang·log4j
无关86883 小时前
Redis Bitmaps 用户签到系统设计方案
数据库·redis·缓存
不爱编程的小陈5 小时前
深入解析 Go 网络 I/O 的底层引擎:从 epoll 到 netpoll
服务器·网络·golang
zzz_23688 小时前
【Java基础】链表的七十二变——从LRU缓存到手写浏览器前进后退
java·链表·缓存
何以解忧,唯有..8 小时前
Go 语言数据类型详解:从基础到复合类型
开发语言·golang·mfc
踏着七彩祥云的小丑9 小时前
Go学习第7天:Map集合 + 递归函数 + 类型转换
开发语言·学习·golang·go
何以解忧,唯有..9 小时前
Go语言变量的声明方式详解
开发语言·后端·golang
寂夜了无痕9 小时前
Go 多版本管理工具G 保姆级安装配置教程
golang·go多版本管理
张忠琳10 小时前
【Go 1.26.4】Golang Slice 深度解析
开发语言·后端·golang
IT策士10 小时前
Redis 从入门到精通:缓存经典难题 —— 穿透、击穿、雪崩
数据库·redis·缓存