[解题报告]LRU Cache

题目链接
题目要求实现一个大小为Capacity,操作复杂度在O(1)的缓存列表,缓存规则:
1 放入数据,并且无论是覆盖放入还是新增的放入,均认为其是最新的数据
2 取得数据,并且若获取成功,则认为它是最新被取得过的数据
3 与规则中“最新”的概念相对应“最旧”概念,若放入数据时缓存列表超过上限Capacity,则需要移除一个“最旧”的数据

基本思路:LRU cache,使用一个双端链表+hashmap实现,“更新至最新”,“移除最旧”,“查找数据本身”均可通过常数级O(1)的时间复杂度实现

双端链表存储结构:数据本身+对应在hashmap中的key,其中key用来移除时快速寻找hashmap内位置
hashmap存储结构:key和数据在链表中元素的地址,用于O(1)的速度找到对应链表内的节点以进行后续操作

Runtime: 124 ms (beats 66.7%)
Memory Usage: 18.6 MB

type dataItem struct {
	value int
	key int
}

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

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

func (this *LRUCache) Get(key int) int {
	if v, ok := this.hashMap[key]; ok {
		this.linkList.MoveToFront(v)
		return v.Value.(*dataItem).value
	}
	return -1
}

func (this *LRUCache) Put(key int, value int)  {
	if v, ok := this.hashMap[key]; ok { // if exist update value & move to front
		v.Value = &dataItem{value, key}
		this.linkList.MoveToFront(v)
		return
	}
	if this.linkList.Len() >= this.cap { // if overflow, remove back element
		realEle := this.linkList.Back().Value.(*dataItem)
		if realEle != nil {
			if _, ok := this.hashMap[realEle.key]; ok {
				delete(this.hashMap, realEle.key)
			}
		}
		this.linkList.Remove(this.linkList.Back())
	}
	this.hashMap[key] = this.linkList.PushFront(&dataItem{value, key})
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * obj := Constructor(capacity);
 * param_1 := obj.Get(key);
 * obj.Put(key,value);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值