通过Golang的container/list实现LRU缓存算法

文章目录

    • 力扣:146. LRU 缓存
    • 主要结构 List 和 Element
      • 常用方法
      • 1. 初始化链表
      • 2. 插入元素
      • 3. 删除元素
      • 4. 遍历链表
      • 5. 获取链表长度
      • 使用场景
      • 注意事项
    • 源代码阅读

在 Go 语言中,container/list 包提供了一个双向链表的实现。链表是一种常见的数据结构,适用于频繁插入和删除操作的场景。container/list 包中的链表是双向的,意味着每个元素都包含指向前一个和后一个元素的指针。

力扣:146. LRU 缓存

力扣算法链接:https://leetcode.cn/problems/lru-cache/?envType=study-plan-v2&envId=top-100-liked

请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存。
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。

函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

输入
[“LRUCache”, “put”, “put”, “get”, “put”, “get”, “put”, “get”, “get”, “get”]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]

输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4

代码案例:

type Node struct {key   intvalue int
}type LRUCache struct {capacity intlist     *list.Listmp       map[int]*list.Element
}func Constructor(capacity int) LRUCache {return LRUCache{capacity: capacity,list:     list.New(),mp:       make(map[int]*list.Element),}
}func (this *LRUCache) Get(key int) int {if v, ok := this.mp[key]; ok {this.list.MoveToFront(v)return v.Value.(*Node).value}return -1
}func (this *LRUCache) Put(key int, value int) {if v, ok := this.mp[key]; ok {v.Value.(*Node).value = valuethis.list.MoveToFront(v)return}node := &Node{key, value}a := this.list.PushFront(node)this.mp[key] = aif this.list.Len() > this.capacity {tmp := this.list.Back()delete(this.mp, tmp.Value.(*Node).key)this.list.Remove(tmp)}
}

主要结构 List 和 Element

  • List: 表示一个双向链表。
type List struct {root Element // sentinel list element, only &root, root.prev, and root.next are usedlen  int     // current list length excluding (this) sentinel element
}
  • Element: 表示链表中的一个元素。
type Element struct {next, prev *Elementlist *ListValue any
}

常用方法

1. 初始化链表

使用 list.New() 创建一个新的链表。

func main() {l := list.New()fmt.Printf("%+v\n",l)
}

在这里插入图片描述

2. 插入元素

  • PushBack(value interface{}) *Element: 在链表尾部插入一个元素。
  • PushFront(value interface{}) *Element: 在链表头部插入一个元素。
  • InsertBefore(value interface{}, mark *Element) *Element: 在指定元素前插入一个元素。
  • InsertAfter(value interface{}, mark *Element) *Element: 在指定元素后插入一个元素。
func main() {l := list.New()l.PushBack(123)l.PushBack("nihao")l.PushFront("你好")l.PushFront(3.1415926)// 遍历for e := l.Front(); e != nil; e = e.Next() {fmt.Printf("%+v\n", e)}
}

通过运行结果可以发现,list其实就是一个环形的双向链表。
在这里插入图片描述

3. 删除元素

  • Remove(e *Element) interface{}: 删除链表中的指定元素。
func main() {l := list.New()l.PushBack("nihao")a:=l.Remove(l.Back())fmt.Println(a)
}

在这里插入图片描述

4. 遍历链表

  • Front() *Element: 返回链表的第一个元素。
  • Back() *Element: 返回链表的最后一个元素。
  • Next() *Element: 返回当前元素的下一个元素。
  • Prev() *Element: 返回当前元素的前一个元素。
func main() {l := list.New()l.PushBack(1)l.PushBack(2)l.PushBack(3)// 从前往后遍历for e := l.Front(); e != nil; e = e.Next() {fmt.Println(e.Value)}// 从后往前遍历for e := l.Back(); e != nil; e = e.Prev() {fmt.Println(e.Value)}
}

5. 获取链表长度

  • Len() int: 返回链表中元素的个数。
func main() {l := list.New()l.PushBack(1)l.PushBack(2)l.PushBack(3)fmt.Println(l.Len()) // 输出: 3
}

使用场景

  • 频繁插入和删除: 链表在插入和删除操作上比数组更高效,尤其是在中间位置。
  • 实现队列和栈: 链表可以用来实现队列(FIFO)和栈(LIFO)等数据结构。
  • 动态数据存储: 当数据量不确定或需要动态调整时,链表是一个很好的选择。

注意事项

  • 内存开销: 链表的每个元素都需要额外的内存来存储前后指针,因此内存开销比数组大。
  • 随机访问性能差: 链表不支持随机访问,访问某个元素需要从头或尾开始遍历。

源代码阅读

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.// Package list implements a doubly linked list.
//
// To iterate over a list (where l is a *List):
//
//	for e := l.Front(); e != nil; e = e.Next() {
//		// do something with e.Value
//	}
package list// Element is an element of a linked list.
type Element struct {//双链表元素中的下一个和上一个指针。//为了简化实现,在内部实现了列表l//作为一个环,这样&l.root既是最后一个元素的下一个元素//list元素(l.Back())和第一个列表的前一个元素//元素(l.Front())。next, prev *Element// The list to which this element belongs.list *List// The value stored with this element.Value any
}// Next returns the next list element or nil.
func (e *Element) Next() *Element {if p := e.next; e.list != nil && p != &e.list.root {return p}return nil
}// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element {if p := e.prev; e.list != nil && p != &e.list.root {return p}return nil
}// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List struct {root Element // sentinel list element, only &root, root.prev, and root.next are usedlen  int     // current list length excluding (this) sentinel element
}// Init initializes or clears list l.
func (l *List) Init() *List {l.root.next = &l.rootl.root.prev = &l.rootl.len = 0return l
}// New returns an initialized list.
func New() *List { return new(List).Init() }// Len returns the number of elements of list l.
// The complexity is O(1).
func (l *List) Len() int { return l.len }// Front returns the first element of list l or nil if the list is empty.
func (l *List) Front() *Element {if l.len == 0 {return nil}return l.root.next
}// Back returns the last element of list l or nil if the list is empty.
func (l *List) Back() *Element {if l.len == 0 {return nil}return l.root.prev
}// lazyInit lazily initializes a zero List value.
func (l *List) lazyInit() {if l.root.next == nil {l.Init()}
}// insert inserts e after at, increments l.len, and returns e.
func (l *List) insert(e, at *Element) *Element {e.prev = ate.next = at.nexte.prev.next = ee.next.prev = ee.list = ll.len++return e
}// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
func (l *List) insertValue(v any, at *Element) *Element {return l.insert(&Element{Value: v}, at)
}// remove removes e from its list, decrements l.len
func (l *List) remove(e *Element) {e.prev.next = e.nexte.next.prev = e.preve.next = nil // avoid memory leakse.prev = nil // avoid memory leakse.list = nill.len--
}// move moves e to next to at.
func (l *List) move(e, at *Element) {if e == at {return}e.prev.next = e.nexte.next.prev = e.preve.prev = ate.next = at.nexte.prev.next = ee.next.prev = e
}// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
// The element must not be nil.
func (l *List) Remove(e *Element) any {if e.list == l {// if e.list == l, l must have been initialized when e was inserted// in l or l == nil (e is a zero Element) and l.remove will crashl.remove(e)}return e.Value
}// PushFront inserts a new element e with value v at the front of list l and returns e.
func (l *List) PushFront(v any) *Element {l.lazyInit()return l.insertValue(v, &l.root)
}// PushBack inserts a new element e with value v at the back of list l and returns e.
func (l *List) PushBack(v any) *Element {l.lazyInit()return l.insertValue(v, l.root.prev)
}// InsertBefore inserts a new element e with value v immediately before mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertBefore(v any, mark *Element) *Element {if mark.list != l {return nil}// see comment in List.Remove about initialization of lreturn l.insertValue(v, mark.prev)
}// InsertAfter inserts a new element e with value v immediately after mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertAfter(v any, mark *Element) *Element {if mark.list != l {return nil}// see comment in List.Remove about initialization of lreturn l.insertValue(v, mark)
}// MoveToFront moves element e to the front of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToFront(e *Element) {if e.list != l || l.root.next == e {return}// see comment in List.Remove about initialization of ll.move(e, &l.root)
}// MoveToBack moves element e to the back of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToBack(e *Element) {if e.list != l || l.root.prev == e {return}// see comment in List.Remove about initialization of ll.move(e, l.root.prev)
}// MoveBefore moves element e to its new position before mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveBefore(e, mark *Element) {if e.list != l || e == mark || mark.list != l {return}l.move(e, mark.prev)
}// MoveAfter moves element e to its new position after mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveAfter(e, mark *Element) {if e.list != l || e == mark || mark.list != l {return}l.move(e, mark)
}// PushBackList inserts a copy of another list at the back of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushBackList(other *List) {l.lazyInit()for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {l.insertValue(e.Value, l.root.prev)}
}// PushFrontList inserts a copy of another list at the front of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushFrontList(other *List) {l.lazyInit()for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {l.insertValue(e.Value, &l.root)}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/72837.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【大学生体质】智能 AI 旅游推荐平台(Vue+SpringBoot3)-完整部署教程

智能 AI 旅游推荐平台开源文档 项目前端地址 ☀️项目介绍 智能 AI 旅游推荐平台(Intelligent AI Travel Recommendation Platform)是一个利用 AI 模型和数据分析为用户提供个性化旅游路线推荐、景点评分、旅游攻略分享等功能的综合性系统。该系统融合…

【渗透测试】基于时间的盲注(Time-Based Blind SQL Injection)

发生ERROR日志告警 查看系统日志如下: java.lang.IllegalArgumentException: Illegal character in query at index 203: https://api.weixin.qq.com/sns/jscode2session?access_token90_Vap5zo5UTJS4jbuvneMkyS1LHwHAgrofaX8bnIfW8EHXA71IRZwsqzJam9bo1m3zRcSrb…

redis数据类型以及底层数据结构

redis数据类型以及底层数据结构 String:字符串类型,底层就是动态字符串,使用sds数据结构 Map:有两种数据结构:1.压缩列表:当hash结构中存储的元素个数小于了512个。并且元 …

DeepSeek R1-32B医疗大模型的完整微调实战分析(全码版)

DeepSeek R1-32B微调实战指南 ├── 1. 环境准备 │ ├── 1.1 硬件配置 │ │ ├─ 全参数微调:4*A100 80GB │ │ └─ LoRA微调:单卡24GB │ ├── 1.2 软件依赖 │ │ ├─ PyTorch 2.1.2+CUDA │ │ └─ Unsloth/ColossalAI │ └── 1.3 模…

window下的docker内使用gpu

Windows 上使用 Docker GPU需要进行一系列的配置和步骤。这是因为 Docker 在 Windows 上的运行环境与 Linux 有所不同,需要借助 WSL 2(Windows Subsystem for Linux 2)和 NVIDIA Container Toolkit 来实现 GPU 的支持。以下是详细的流程: 一、环境准备 1.系统要求 Window…

Ubuntu 下 nginx-1.24.0 源码分析 - cycle->modules[i]->type

Nginx 中主要有以下几种模块类型 类型 含义 NGX_CORE_MODULE 核心模块(如进程管理、错误日志、配置解析)。 NGX_EVENT_MODULE 事件模块(如 epoll、kqueue 等 IO 多路复用机制的实现)。 NGX_HTTP_MODULE HTTP 模块&#xf…

八、排序算法

一些简单的排序算法 8.1 冒泡排序 void Bubble_sort(int a[] , int len){int i,j,flag,tmp;for(i=0 ; i < len-1 ; i++){flag = 1;for(j=0 ; j < len-1-i ; j++){if(a[j] > a[j+1]){tmp = a[j];a[j] = a[j+1];a[j+1] = tmp;flag = 0;}}if(flag == 1){break;}}…

Sqlserver安全篇之_手工创建TLS用到的pfx证书文件

Sqlserver官方提供的Windows Powershell脚本 https://learn.microsoft.com/zh-cn/sql/database-engine/configure-windows/configure-sql-server-encryption?viewsql-server-ver16 # Define parameters $certificateParams {Type "SSLServerAuthentication"Subje…

npm install -g @vue/cli 方式已经无法创建VUE3项目

采用该方式&#xff0c;启动VUE3项目&#xff0c;运行命令&#xff0c;出现报错&#xff1a; npm install -g vue/cli PS D:\> npm install -g vue/cli npm warn deprecated inflight1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lr…

3.8[a]cv

函数核心目标 实现屏幕空间内三角形的光栅化&#xff0c;将三角形覆盖的像素点颜色填充到帧缓冲区&#xff0c;同时处理深度测试&#xff08;Z-Buffer&#xff09;。这是渲染管线中几何阶段到像素阶段的关键步骤 包围盒计算&#xff08;Bounding Box&#xff09;​** ​功能&…

导入 Excel 规则批量修改或删除 Excel 表格内容

我们前面介绍过按照规则批量修改 Excel 文档内容的操作&#xff0c;可以对大量的 Excel 文档按照一定的规则进行统一的修改&#xff0c;可以很好的解决我们批量修改 Excel 文档内容的需求。但是某些场景下&#xff0c;我们批量修改 Excel 文档内容的场景比较复杂&#xff0c;比…

SGLang Router:基于缓存感知负载均衡的数据并行路由实践

SGLang Router&#xff1a;基于缓存感知负载均衡的数据并行路由实践 一、引言二、安装与快速启动三、两种工作模式对比3.1 协同启动模式&#xff08;单节点&#xff09;3.2 独立启动模式&#xff08;多节点&#xff09; 四、动态扩缩容API4.1 添加Worker节点4.2 移除Worker节点…

在人工智能软件的帮助下学习编程实例

1 引言 本文记录在人工智能软件的帮助下学习一种全新的编程环境的实例&#xff0c;之所以提人工智能软件而不是单指DeepSeek&#xff0c;一方面DeepSeek太火了&#xff0c;经常服务器繁忙&#xff0c;用本机本地部署的最多运行70b模型&#xff0c;又似乎稍差。另一方面也作为一…

Ubuntu 下 nginx-1.24.0 源码分析 - ngx_modules

定义在 objs\ngx_modules.c #include <ngx_config.h> #include <ngx_core.h>extern ngx_module_t ngx_core_module; extern ngx_module_t ngx_errlog_module; extern ngx_module_t ngx_conf_module; extern ngx_module_t ngx_openssl_module; extern ngx_modul…

深度学习代码解读——自用

代码来自&#xff1a;GitHub - ChuHan89/WSSS-Tissue 借助了一些人工智能 2_generate_PM.py 功能总结 该代码用于 生成弱监督语义分割&#xff08;WSSS&#xff09;所需的伪掩码&#xff08;Pseudo-Masks&#xff09;&#xff0c;是 Stage2 训练的前置步骤。其核心流程为&a…

Java基础面试题全集

1. Java语言基础 1.1 Java是什么&#xff1f; • Java是一种广泛使用的编程语言&#xff0c;最初由Sun Microsystems&#xff08;现为Oracle公司的一部分&#xff09;于1995年发布。它是一种面向对象的、基于类的、通用型的编程语言&#xff0c;旨在让应用程序“编写一次&…

Selenium遇到Exception自动截图

# 随手小记 场景&#xff1a;测试百度&#xff1a; 点击新闻&#xff0c;跳转到新的窗口&#xff0c;找到输入框&#xff0c;输入“hello,world" 等到输入框的内容是hello,world, 这里有个错误&#xff0c;少了一个] 后来就实现了错误截图的功能&#xff0c;可以参考 …

【神经网络】python实现神经网络(一)——数据集获取

一.概述 在文章【机器学习】一个例子带你了解神经网络是什么中&#xff0c;我们大致了解神经网络的正向信息传导、反向传导以及学习过程的大致流程&#xff0c;现在我们正式开始进行代码的实现&#xff0c;首先我们来实现第一步的运算过程模拟讲解&#xff1a;正向传导。本次代…

Sentinel 笔记

Sentinel 笔记 1 介绍 Sentinel 是阿里开源的分布式系统流量防卫组件&#xff0c;专注于 流量控制、熔断降级、系统保护。 官网&#xff1a;https://sentinelguard.io/zh-cn/index.html wiki&#xff1a;https://github.com/alibaba/Sentinel/wiki 对比同类产品&#xff1…

manus本地部署方法研究测试

Manus本地部署方法&#xff0c;Manus邀请码实在太难搞了&#xff0c;昨晚看到有一个团队&#xff0c;5个人3个小时&#xff0c;一个完全免费、无需排队等待的OpenManus就做好了。 由于也是新手&#xff0c;找了好几轮&#xff0c;实在是没有找到合适的部署方法&#xff0c;自己…