LRU Cache (M)
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:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
题意
实现一个LRU缓存机制:查询时,如果不存在目标key,则返回-1,否则返回key对应的value;插入时,如果缓存已满,则将访问时间最远的(key, value)对删去,存入新的(key, value)对。
思路
主要思想是维护一个类数组结构,越近访问的数据越靠近头部,越远访问的数据越靠近尾部。每次查询到旧值或访问新值时,将该值从原位置取出并插入到头部;需要删除数据时,只要删去尾部的数据。
具体实现使用双向链表+HashMap:双向链表使得删除和移动结点的复杂度为 O ( 1 ) O(1) O(1);HashMap用于创建索引,将key值映射到对应的结点,使结点查询复杂度也为 O ( 1 ) O(1) O(1)。
代码实现
class LRUCache {
// 双向链表结点
class Node {
int key, val;
Node prev, next;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
private Node head, tail;
private int capacity;
private Map<Integer, Node> hash;
public LRUCache(int capacity) {
this.capacity = capacity;
hash = new HashMap<>();
// dummy结点可以大大简化步骤
head = new Node(-1, -1);
tail = new Node(-1, -1);
head.next = tail;
}
public int get(int key) {
if (!hash.containsKey(key)) {
return -1;
}
// 查询到存在,则将原结点拎出插入到头结点之后
Node target = hash.get(key);
removeFromPos(target);
moveToFirst(target);
return target.val;
}
public void put(int key, int value) {
if (!hash.containsKey(key)) {
// 需要插入新值,则新建结点并将其移动到头结点后
Node temp = new Node(key, value);
hash.put(key, temp);
moveToFirst(temp);
} else {
// 更新旧值,并将原结点取出插入到头结点之后
Node target = hash.get(key);
target.val = value;
removeFromPos(target);
moveToFirst(target);
}
// 超出容量,则删去尾结点之前的结点
if (hash.size() == capacity + 1) {
hash.remove(tail.prev.key);
removeFromPos(tail.prev);
}
}
// 将目标结点移动到头结点之后
private void moveToFirst(Node target) {
target.next = head.next;
head.next.prev = target;
target.prev = head;
head.next = target;
}
// 将目标结点从链中取出
private void removeFromPos(Node target) {
target.prev.next = target.next;
target.next.prev = target.prev;
target.next = null;
target.prev = null;
}
}