golang實現LRU演算法

2022-09-21 02:48:09 字數 1632 閱讀 5507

least recently used

本文僅列出完成 leetcode146.lru快取的思路

實現:實現lru並不難,建議先把演算法的各個函式的框架先列好,再去敲**!!

結構:

//lrucache定義

type lrucache struct

//雙向鍊錶節點

type dlinknode struct

功能:

//快取實現的功能

//如果關鍵字 key 存在於快取中,則返回關鍵字的值,否則返回 -1 。

func (this *lrucache) get(key int)

//如果關鍵字 key 已經存在,則變更其資料值 value ;如果不存在,則向快取中插入該組 key-value 。如果插入操作導致關鍵字數量超過 capacity ,則應該 逐出最久未使用的關鍵字

func (this *lrucache) put(key int, value int)

//一些鍊錶的操作

//初始化乙個新節點

func initdlinkednode(key, value int) *dlinknode

//更新到鏈頭,用於key命中的情況下,不改變快取的size

func (this *lrucache) updatetohead(node *dlinknode)

//刪除鏈尾元素

func (this *lrucache) deletelast()

//新增新元素,用於key未命中時,size+1

func (this *lrucache) insertnewhead(node *dlinknode)

以下附上完整**

type lrucache struct 

type dlinknode struct

func initdlinknode(key, value int) *dlinknode

}func constructor(capacity int) lrucache ,

initdlinknode(0, 0),

initdlinknode(0, 0),

}l.head.next = l.tail

l.tail.pre = l.head

return l

}func (this *lrucache) get(key int) int

node := this.cache[key]

this.updatetohead(node)

return node.value

}func (this *lrucache) put(key int, value int)

this.cache[key] = node

this.insertnewhead(node)

}else

}func (this *lrucache) updatetohead(node *dlinknode)

func (this *lrucache) deletelast()

func (this *lrucache) insertnewhead(node *dlinknode)

golang使用雙向鍊錶實現LRU演算法

使用雙向鍊錶實現的lru演算法 type lrucache struct 鍊錶節點 type dbnode struct 雙向鍊錶 type dblist struct 往鍊錶頭部插入資料 if node nil d.mutex.rlock defer d.mutex.runlock if d.si...

LRU演算法實現

jdk 中的實現 在jdk 中linkedhashmap 可以作為lru 演算法以及插入順序的實現,linkedhashmap 繼承自hashmap 底層結合hash 表和雙向鍊錶,元素的插入和查詢等操作通過計算hash 值找到其陣列位置,在做插入或則查詢操作是,將元素插入到鍊錶的表頭 當然得先刪除...

LRU演算法的實現

0 推薦 lru演算法的實現 什麼是lru演算法lru是least recently used的縮寫,即最近最少使用頁面置換演算法,是為虛擬頁式儲存管理服務的.關於作業系統的記憶體管理,如何節省利用容量不大的記憶體為最多的程序提供資源,一直是研究的重要方向.而記憶體的虛擬儲存管理,是現在最通用,最成...