LRU缓存机制

lru算法思路:
首先思考lru最近最久未使用算法,
1、操作内容
2、数据结构
有两部分操作是比较关键的
1、查询操作
2、插入删除操作
考虑如何建立结构体让这个算法的时间复杂度最少
查询操作时间复杂度最少首当其冲hash结构,因此一定离不开hash的结构体(时间复杂度O(1))
插入删除操作时间复杂度最少,一定是链表结构,考虑实际使用场景需要对队列头尾进行同时操作,因此选择双端链表(时间复杂度O(1))
type ListNode struct{
	key int
	value int
	pre *ListNode
	next *ListNode
}

type LRUCache struct {
	len int
	Node map[int]*ListNode
	head *ListNode
	tailf *ListNode
}


func Constructor(capacity int) LRUCache {
	LruNode := LRUCache{
		len : capacity,
		Node : make(map[int]*ListNode),
		head : &ListNode{},
		tailf : &ListNode{},
	}
	LruNode.head.next = LruNode.tailf
	LruNode.tailf.pre = LruNode.head
	return LruNode
}

func (this *LRUCache)pushead(node *ListNode) {
	node.next = this.head.next
	this.head.next.pre = node
	this.head.next = node
	node.pre = this.head
}

func (this *LRUCache)removeNode (node *ListNode) {
	node.pre.next = node.next
	node.next.pre = node.pre
}

func (this *LRUCache) Get(key int) int {
	if v,ok :=this.Node[key] ;ok {
		this.removeNode(v)
		this.pushead(v)
		return v.value
	} else {
		return -1
	}
}


func (this *LRUCache) Put(key int, value int)  {
	newnode := new(ListNode)
	newnode.key = key
	newnode.value = value
	if v,ok :=this.Node[key] ;ok {
		this.removeNode(v)
		this.pushead(newnode)
		this.Node[key] = newnode
	} else {
		if len(this.Node) == this.len {
			delete(this.Node,this.tailf.pre.key)
			this.removeNode(this.tailf.pre)
			this.pushead(newnode)
			this.Node[key] = newnode
		} else {
			this.pushead(newnode)
			this.Node[key] = newnode
		}
	}
}
### LRU缓存机制工作原理 LRU(Least Recently Used,最近最少使用)是一种常用的页面置换算法。当物理内存块不足以容纳所有正在执行的程序所需分配的空间时操作系统将寻找最长时间未被使用的页面将其移出内存。在缓存场景下,LRU用于决定哪些数据项应被淘汰以腾出空间给新加入的数据项。 为了实现高效的`get`和`put`操作,通常采用哈希表与双向链表相结合的方式[^3]。具体来说: - **哈希表**:提供快速查找功能,键映射到对应的节点位置。 - **双向链表**:维护元素顺序,头部表示最新访问过的元素而尾部则是最久未使用的元素。 每次调用`get(key)`方法获取某个key对应value的同时也会更新此条目至链表头端表明它是刚被访问过的内容;每当执行`put(key,value)`插入新的KV对或者覆盖已有记录时同样要调整相应结点的位置确保它成为最新的项目之一。一旦超出预设的最大容量(capacity),就自动删除位于列表末端代表最旧的那个entry来释放资源。 以下是基于上述描述的一个Python版本的具体实现示例: ```python from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.cache = OrderedDict() self.capacity = capacity def get(self, key: int) -> int: if key not in self.cache: return -1 val = self.cache.pop(key) # Move the accessed item to the end. self.cache[key] = val return val def put(self, key: int, value: int) -> None: if key in self.cache: del self.cache[key] elif len(self.cache) >= self.capacity: # Pop the first element as it is least recently used. old_key = next(iter(self.cache)) del self.cache[old_key] self.cache[key] = value # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) ``` 这段代码利用了 Python 内置模块 `OrderedDict`, 它可以记住字典中元素添加的先后次序,并支持通过 `.popitem(last=False)` 方法弹出最早插入的那一项从而达到淘汰策略的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值