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
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值