算法8:LRU Cache

2021-03-17  本文已影响0人  HYIndex

LeetCode No.146 LRU缓存机制

LRU(Least Recent Used)策略:优先淘汰最近最少使用的数据,常用于缓存淘汰机制,如Linux系统的内存淘汰、Redis的缓存淘汰等。

基于哈希表和双向链表实现LRU

核心思路是,利用双向链表存储键值对,哈希表存储键在链表中对应的节点指针,如下图所示


这样的好处是使访问和更新操作时间复杂度都在O(1)。

PUT操作

GET操作

Go语言实现

使用Go内建map类型和container包的list(双向链表)

import (
    "container/list"
)

type Pair struct {
    key int
    val int
}

type LRUCache struct {
    cap int
    list *list.List
    kv map[int]*list.Element
}


func Constructor(capacity int) LRUCache {
    return LRUCache{
        cap: capacity,
        list: list.New(),
        kv: make(map[int]*list.Element),
    }
}


func (this *LRUCache) Get(key int) int {
    if v, ok := this.kv[key]; ok == true {
        this.list.MoveToFront(v)
        return v.Value.(Pair).val
    } else {
        return -1
    }
}


func (this *LRUCache) Put(key int, value int)  {
    if elem, ok := this.kv[key]; ok == true {
        elem.Value = Pair{key: key, val: value}
        this.list.MoveToFront(elem)
        return
    }
    if this.list.Len() >= this.cap {
        delete(this.kv, this.list.Back().Value.(Pair).key)
        this.list.Remove(this.list.Back())
    }
    this.list.PushFront(Pair{key: key, val: value})
    this.kv[key] = this.list.Front()
}
上一篇 下一篇

猜你喜欢

热点阅读