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缓存机制
最新推荐文章于 2024-07-14 19:56:17 发布