Lintcode134 Lru Cache solution 题解

【题目描述】

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:getandset.

get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

set(key, value)- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

为最近最少使用(LRU)缓存策略设计一个数据结构,它应该支持以下操作:获取数据(get)和写入数据(set)。

获取数据get(key):如果缓存中存在key,则获取其数据值(通常是正数),否则返回-1。

写入数据set(key, value):如果key还没有在缓存中,则写入其数据值。当缓存达到上限,它应该在写入新数据之前删除最近最少使用的数据用来腾出空闲位置。

【题目链接】

www.lintcode.com/en/problem/lru-cache/

【题目解析】

LRU cache数据结构的核心就是当存储空间满了,而有新的item要插入时,要先丢弃最早更新的item。这里的数据结构需要符合以下条件:

1、要能快速找到最早更新的item。这里需要将item以更新时间顺序排序。 可选的有:queue,heap,linked list。

2、要能快速访问指定item,并且访问以后要更新它的时间顺序。 对于更新时间顺序这个操作,queue和heap要做到就很困难了。所以这点最佳的是linked list。但linked list中查找指定item需要遍历,这里可以用一个hash table来记录key与节点之间的对应。并且由于要随时更新节点位置,doubly linked list更为适用。(也可以不用doubly linked list, 在hashmap总存listnode的前一个,并且用head和tail来track list的头尾就可以)。

3、linked list最尾部的表示最新访问的get(key)。把node放到尾部,读取value set(key, value)。如果key已经有了,放到尾部,更新value;如果key还没有,放到尾部;如果size > capacity, 讲头部的node pop掉,因为头部和尾部都不确定,所以就像linkedlist要有dummy node一样,要有一个head和tail head一直不变,指向第一个node(表示least recently used) tail一直指向最后一个node,每次更新(表示mose recently used)。

【参考答案】

www.jiuzhang.com/solutions/lru-cache/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值