Lintcode134 Lru Cache solution 题解

来源:互联网 发布:c语言二维数组赋值 编辑:程序博客网 时间:2024/06/03 22:59

【题目描述】

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/



原创粉丝点击