题目概述
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.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
1 | LRUCache cache = new LRUCache( 2 /* capacity */ ); |
本题本质上就是模拟cache的替换策略。当cache没有满时进行put操作会直接按顺序将cache填充满,如果cache满后进行put操作,将会替代掉最先使用的key的信息。
所以本题就是维护一个数组keys,这个数组的最左边的key为最先使用的key,最右边则为最近使用的key。同时,还需要用一个keyMap来存放所有key对应的value值。我令所有的key最初为-1,在进行put(key, value)操作时:
- 如果数组keys中存在这个key时,把这个key右边的所有信息左移一格。然后在所有有效信息(非-1信息)的最右边加上这个key,保证数组能够存储keys的使用先后信息
- 如果keys中不存在这个key,并且keys数组没有满,则在所有有效信息的最右边加上这个key
- 如果keys中不存在这个key,并且keys数组已满,则将最左边的key删除,把所有的key向左移动一格,最后在最右边加上这个key
在进行get(key)操作时候:
- 如果keys不存在这个key,则返回-1
- 如果keys存在这个key,按照put才做中的1来操作keys数组,并且在keyMap中查找对应的值进行返回
代码实现
1 | class LRUCache { |