【Leetcode】146. LRU Cache

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

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

put(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.


【Leetcode】146. LRU Cache_第1张图片

1 要用到OrderedDict class

2 在init里面,初始化一个array,是OrderedDict类型的;同时初始化capacity,capacity的值是参数传进来的

3 LRU根据数据的历史访问记录来进行数据的淘汰,如果数据最近被访问过,那么将来被访问的几率也高

4 此题要求O(1)时间复杂度,所以使用双链表

5 如果发生了缺页,应该将最近最久未被访问的页置换出去

6 把最近最久没有使用的数据放在链表的最后,当缓存空间满时,即发生缺页,直接将最后一个数据淘汰即可

7 如果一个数据命中或者新来一个数据时,我们把该数据移到链表的头部,这样就能保证链表头部的数据都是最近访问过的,链表后面的数据是最近最久没有访问过的

8 LRU介绍:https://www.cnblogs.com/bakari/p/4016318.html

9 在写get函数时,需要将之前的key删除,再重新添加进去

10 k,v = self.array.iteritems().next() 这里就是第一个element,也是least recent used element


【Leetcode】146. LRU Cache_第2张图片


【Leetcode】146. LRU Cache_第3张图片

1 构建一个OrderedDict,是有先后顺序的

2 get的时候,因为用到这个key了,所以需要先删了它,然后再添加在最近的位置

3 put的时候,如果key在dic中,则需要先将其删除,然后再添加;如果不在dic中,则需要看dic是否已经到capacity了,如果达到了,需要先删除recently least used,最后再添加

4 这里用到迭代器和next函数


【Leetcode】146. LRU Cache_第4张图片

调用iterator的next函数时,是这样的next(iterator),要把iterator放在next的里面

还有一个小bug是,使用next函数产生key的时候,要注意不要用key关键字,因为输入key就是用的key这个词

你可能感兴趣的:(【Leetcode】146. LRU Cache)