通過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.pswp.cn/bicheng/72837.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/72837.shtml
英文地址,請注明出處:http://en.pswp.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;自己…