146. LRU Cache
题目大意
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache
class:
LRUCache(int capacity)
Initialize the LRU cache with positive size capacity.int get(int key)
Return the value of the key if the key exists, otherwise return -1.void put(int key, int value)
Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get
and put
must each run in O(1) average time complexity.
中文释义
设计一个遵循最近最少使用(LRU)缓存约束的数据结构。
实现 LRUCache
类:
LRUCache(int capacity)
用正整数容量初始化 LRU 缓存。int get(int key)
如果键存在,则返回键的值;否则,返回 -1。void put(int key, int value)
如果键存在,更新其值。否则,将键值对添加到缓存中。如果此操作导致键的数量超出容量,那么淘汰最近最少使用的键。
get
和 put
函数必须都具有 O(1) 的平均时间复杂度。
示例
示例 1:
输入
[“LRUCache”, “put”, “put”, “get”, “put”, “get”, “put”, “get”, “get”, “get”]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]
解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // LRU键是2,淘汰键2,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // LRU键是1,淘汰键1,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
限制条件
- 容量范围为
1 <= capacity <= 3000
。 - 键的范围为
0 <= key <= 104
。 - 值的范围为
0 <= value <= 105
。 - 最多将对
get
和put
调用 2 * 10^5 次。
解题思路
方法
该方案使用双数据结构:一个双向链表ÿ