最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何通過Golang的container/list實(shí)現(xiàn)LRU緩存算法

 更新時間:2025年03月12日 11:27:17   作者:萬里code  
文章介紹了Go語言中container/list包實(shí)現(xiàn)的雙向鏈表,并探討了如何使用鏈表實(shí)現(xiàn)LRU緩存,LRU緩存通過維護(hù)一個雙向鏈表來管理數(shù)據(jù),確保在插入和刪除操作時能夠以O(shè)(1)的平均時間復(fù)雜度運(yùn)行,提供了鏈表的操作和使用場景,并附帶了實(shí)現(xiàn)LRU緩存的代碼示例,感興趣的朋友一起看看吧

在 Go 語言中,container/list 包提供了一個雙向鏈表的實(shí)現(xiàn)。鏈表是一種常見的數(shù)據(jù)結(jié)構(gòu),適用于頻繁插入和刪除操作的場景。container/list 包中的鏈表是雙向的,意味著每個元素都包含指向前一個和后一個元素的指針。

力扣:146. LRU 緩存

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

請你設(shè)計并實(shí)現(xiàn)一個滿足 LRU (最近最少使用) 緩存 約束的數(shù)據(jù)結(jié)構(gòu)。
實(shí)現(xiàn) LRUCache 類:
LRUCache(int capacity) 以 正整數(shù) 作為容量 capacity 初始化 LRU 緩存。
int get(int key) 如果關(guān)鍵字 key 存在于緩存中,則返回關(guān)鍵字的值,否則返回 -1 。
void put(int key, int value) 如果關(guān)鍵字 key 已經(jīng)存在,則變更其數(shù)據(jù)值 value ;如果不存在,則向緩存中插入該組 key-value 。如果插入操作導(dǎo)致關(guān)鍵字?jǐn)?shù)量超過 capacity ,則應(yīng)該 逐出 最久未使用的關(guān)鍵字。

函數(shù) get 和 put 必須以 O(1) 的平均時間復(fù)雜度運(yùn)行。

輸入

[“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); // 該操作會使得關(guān)鍵字 2 作廢,緩存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 該操作會使得關(guān)鍵字 1 作廢,緩存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4

代碼案例:

type Node struct {
	key   int
	value int
}
type LRUCache struct {
	capacity int
	list     *list.List 
	mp       map[int]*list.Element // 注意1:value是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 // 注意2:list.Element里面有一個Value any字段,所以需要斷言
	}
	return -1
}
func (this *LRUCache) Put(key int, value int) {
	if v, ok := this.mp[key]; ok {
		v.Value.(*Node).value = value
		this.list.MoveToFront(v) // 注意3:需要移動,LRU
        return
	}
	node := &Node{key, value}
	a := this.list.PushFront(node)
	this.mp[key] = a // 注意4:一定把插入鏈表的kv,也加入到哈希表
	if this.list.Len() > this.capacity { // 注意5:判斷是否越界
		tmp := this.list.Back()
		delete(this.mp, tmp.Value.(*Node).key) // 注意6:刪除已經(jīng)淘汰的數(shù)據(jù)的key
		this.list.Remove(tmp)
	}
}

主要結(jié)構(gòu) List 和 Element

List: 表示一個雙向鏈表。

type List struct {
	root Element // sentinel list element, only &root, root.prev, and root.next are used
	len  int     // current list length excluding (this) sentinel element
}

Element: 表示鏈表中的一個元素。

type Element struct {
	next, prev *Element
	list *List
	Value any
}

常用方法

1. 初始化鏈表

使用 list.New() 創(chuàng)建一個新的鏈表。

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)
	}
}

通過運(yùn)行結(jié)果可以發(fā)現(xiàn),list其實(shí)就是一個環(huán)形的雙向鏈表。

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: 返回當(dāng)前元素的下一個元素。
  • Prev() *Element: 返回當(dāng)前元素的前一個元素。
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: 返回鏈表中元素的個數(shù)。

func main() {
    l := list.New()
    l.PushBack(1)
    l.PushBack(2)
    l.PushBack(3)
    fmt.Println(l.Len()) // 輸出: 3
}

使用場景

  • 頻繁插入和刪除: 鏈表在插入和刪除操作上比數(shù)組更高效,尤其是在中間位置。
  • 實(shí)現(xiàn)隊列和棧: 鏈表可以用來實(shí)現(xiàn)隊列(FIFO)和棧(LIFO)等數(shù)據(jù)結(jié)構(gòu)。
  • 動態(tài)數(shù)據(jù)存儲: 當(dāng)數(shù)據(jù)量不確定或需要動態(tài)調(diào)整時,鏈表是一個很好的選擇。

注意事項(xiàng)

  • 內(nèi)存開銷: 鏈表的每個元素都需要額外的內(nèi)存來存儲前后指針,因此內(nèi)存開銷比數(shù)組大。
  • 隨機(jī)訪問性能差: 鏈表不支持隨機(jī)訪問,訪問某個元素需要從頭或尾開始遍歷。

源代碼閱讀

// 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 {
	//雙鏈表元素中的下一個和上一個指針。
	//為了簡化實(shí)現(xiàn),在內(nèi)部實(shí)現(xiàn)了列表l
	//作為一個環(huán),這樣&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 used
	len  int     // current list length excluding (this) sentinel element
}
// Init initializes or clears list l.
func (l *List) Init() *List {
	l.root.next = &l.root
	l.root.prev = &l.root
	l.len = 0
	return 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 = at
	e.next = at.next
	e.prev.next = e
	e.next.prev = e
	e.list = l
	l.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.next
	e.next.prev = e.prev
	e.next = nil // avoid memory leaks
	e.prev = nil // avoid memory leaks
	e.list = nil
	l.len--
}
// move moves e to next to at.
func (l *List) move(e, at *Element) {
	if e == at {
		return
	}
	e.prev.next = e.next
	e.next.prev = e.prev
	e.prev = at
	e.next = at.next
	e.prev.next = e
	e.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 crash
		l.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 l
	return 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 l
	return 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 l
	l.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 l
	l.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)
	}
}

到此這篇關(guān)于如何通過Golang的container/list實(shí)現(xiàn)LRU緩存算法的文章就介紹到這了,更多相關(guān)go LRU緩存算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • go-bindata安裝問題及解決

    go-bindata安裝問題及解決

    這篇文章主要介紹了go-bindata安裝問題及解決過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2026-06-06
  • Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放

    Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放

    這篇文章主要為大家介紹了Go語言開發(fā)瀏覽器視頻流rtsp轉(zhuǎn)webrtc播放的過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04
  • 如何利用Golang寫出高并發(fā)代碼詳解

    如何利用Golang寫出高并發(fā)代碼詳解

    今天領(lǐng)導(dǎo)問起為什么用Golang,同事回答語法簡單,語言新,支持高并發(fā)。那高并發(fā)到底如何實(shí)現(xiàn),下面這篇文章主要給大家介紹了關(guān)于如何利用Golang寫出高并發(fā)代碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-09-09
  • Golang函數(shù)的使用技巧(結(jié)合代碼示例)

    Golang函數(shù)的使用技巧(結(jié)合代碼示例)

    函數(shù)是基本的代碼塊,用于執(zhí)行一個任務(wù),這篇文章主要介紹了Golang函數(shù)使用的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2025-11-11
  • golang頻率限制 rate詳解

    golang頻率限制 rate詳解

    這篇文章主要介紹了golang頻率限制 rate詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Golang中urlencode與urldecode編碼解碼詳解

    Golang中urlencode與urldecode編碼解碼詳解

    這篇文章主要給大家介紹了關(guān)于Golang中urlencode與urldecode編碼解碼的相關(guān)資料,在Go語言中轉(zhuǎn)碼操作非常方便,可以使用內(nèi)置的encoding包來快速完成轉(zhuǎn)碼操作,Go語言中的encoding包提供了許多常用的編碼解碼方式,需要的朋友可以參考下
    2023-09-09
  • 詳解如何保留Go程序崩潰現(xiàn)場

    詳解如何保留Go程序崩潰現(xiàn)場

    這篇文章主要為大家介紹了如何保留Go程序崩潰現(xiàn)場示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)解讀

    Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)解讀

    這篇文章主要介紹了Go語言之重要數(shù)組類型切片(slice)make,append函數(shù)用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • GoLand無法Debug問題的解決辦法

    GoLand無法Debug問題的解決辦法

    今天突然要寫下go代碼的項(xiàng)目,突然發(fā)現(xiàn)無法debug,下面這篇文章主要介紹了GoLand無法Debug問題的解決辦法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-10-10
  • Go語言中map使用和并發(fā)安全詳解

    Go語言中map使用和并發(fā)安全詳解

    golang?自帶的map不是并發(fā)安全的,并發(fā)讀寫會報錯,所以下面這篇文章主要給大家介紹了關(guān)于Go語言中map使用和并發(fā)安全的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07

最新評論

武平县| 色达县| 广宗县| 闸北区| 泰兴市| 平泉县| 鄂尔多斯市| 玉山县| 长顺县| 民勤县| 镇宁| 晴隆县| 万山特区| 舞钢市| 徐水县| 油尖旺区| 卢龙县| 铜川市| 汝城县| 乌兰浩特市| 大兴区| 甘孜县| 沂南县| 孝义市| 治县。| 鄂托克前旗| 毕节市| 浦江县| 渭南市| 宁城县| 南阳市| 仲巴县| 南城县| 横山县| 利辛县| 府谷县| 葫芦岛市| 炉霍县| 永昌县| 房产| 内乡县|