国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

golang實現LRU緩存淘汰算法的示例代碼

2020-04-01 18:50:31
字體:
來源:轉載
供稿:網友

LRU緩存淘汰算法

LRU是最近最少使用策略的縮寫,是根據數據的歷史訪問記錄來進行淘汰數據,其核心思想是“如果數據最近被訪問過,那么將來被訪問的幾率也更高”。

雙向鏈表實現LRU

將Cache的所有位置都用雙鏈表連接起來,當一個位置被訪問(get/put)之后,通過調整鏈表的指向,將該位置調整到鏈表頭的位置,新加入的Cache直接加到鏈表頭中。

這樣,在多次操作后,最近被訪問(get/put)的,就會被向鏈表頭方向移動,而沒有訪問的,向鏈表后方移動,鏈表尾則表示最近最少使用的Cache。

當達到緩存容量上限時,鏈表的最后位置就是最少被訪問的Cache,我們只需要刪除鏈表最后的Cache便可繼續添加新的Cache。

代碼實現

type Node struct {  Key int  Value int  pre *Node  next *Node}type LRUCache struct {  limit int  HashMap map[int]*Node  head *Node  end *Node}func Constructor(capacity int) LRUCache{  lruCache := LRUCache{limit:capacity}  lruCache.HashMap = make(map[int]*Node, capacity)  return lruCache}func (l *LRUCache) Get(key int) int {  if v,ok:= l.HashMap[key];ok {    l.refreshNode(v)    return v.Value  }else {    return -1  }}func (l *LRUCache) Put(key int, value int) {  if v,ok := l.HashMap[key];!ok{    if len(l.HashMap) >= l.limit{      oldKey := l.removeNode(l.head)      delete(l.HashMap, oldKey)    }    node := Node{Key:key, Value:value}    l.addNode(&node)    l.HashMap[key] = &node  }else {    v.Value = value    l.refreshNode(v)  }}func (l *LRUCache) refreshNode(node *Node){  if node == l.end {    return  }  l.removeNode(node)  l.addNode(node)}func (l *LRUCache) removeNode(node *Node) int{  if node == l.end {    l.end = l.end.pre  }else if node == l.head {    l.head = l.head.next  }else {    node.pre.next = node.next    node.next.pre = node.pre  }  return node.Key}func (l *LRUCache) addNode(node *Node){  if l.end != nil {    l.end.next = node    node.pre = l.end    node.next = nil  }  l.end = node  if l.head == nil {    l.head = node  }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 沈丘县| 岑巩县| 依兰县| 长丰县| 华容县| 远安县| 剑河县| 马龙县| 门源| 昆明市| 康保县| 将乐县| 利津县| 鄂州市| 白城市| 景宁| 庄浪县| 汉阴县| 小金县| 南安市| 邵阳县| 昌都县| 曲周县| 沈阳市| 永安市| 闽清县| 巨野县| 田阳县| 民权县| 新乡市| 仁寿县| 齐河县| 平舆县| 阜城县| 平罗县| 康平县| 沁源县| 松阳县| 兴隆县| 娱乐| 会东县|