题目描述
这个问题在leetcode146题中有具体介绍,具体为:
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
思路
要在O(1)时间复杂度内完成get和put操作,key与value必须存入到map中,如何确定最近使用最少这一性质呢,这里涉及到最近使用时间的排序问题,每次改动必然导致相关数据的删除,进而优先级顺序发生改变,因此可以考虑使用链表结构,head存储最近一次访问的值,tail存储最后一次访问的value。每次put或者get操作将当前值对应的节点移动到链表的表头。
具体Java语言实现为:采用HashMap存储key与value,双向链表结构表示数据value的访问顺序,为什么必须要用双向链表呢,因为我们需要删除操作,删除一个节点不仅要得到该节点本身的指针,也需要操作其前驱节点的指针,而双向链表才能支持直接查找前驱,保证操作的时间复杂度 O(1)。
head节点便于快速移动到头结点。
由于size的限制,这里tail节点必不可少。
//参考左程云算法视频,对于当前访问的数据放在链表头部,当数据容量超过设定容量时,从头部删除。
leetcode146题答案
package practise;
import java.util.HashMap;
import java.util.Map;
public class LRU {
private int SIZE = 100; //最大容量
private Node first;
private Node tail;
private Map<Integer, Node> map;
class Node {
private int k;
private int v;
private Node next;
private Node pre;
public Node(int k, int v) {
this.k = k;
this.v = v;
}
}
public LRU(int capacity) {
this.SIZE = capacity;
this.map = new HashMap<>();
}
public Integer get(Integer key) {
Node v = map.get(key);
if (v == null) {
return -1;
}
moveToHead(v);
return v.v;
}
private void moveToHead(Node v) {
if (v == first) { // 本身是头结点
return;
} else if(v.next == null){ // 本身是尾节点,更新尾节点
v.pre.next = null;
this.tail = v.pre;
} else {
v.pre.next = v.next;
v.next.pre = v.pre; // 前后节点连在一起
}
v.next = first; // 移到头结点
first.pre = v;
first = v; // 重新定义头结点
}
public void put(Integer k, Integer v) {
Node value = map.get(k);
if (value != null) {
if (value.v != v) {
value.v = v;
}
moveToHead(value);
} else {
Node newValue = new Node(k, v);
addToHead(newValue);
map.put(k, newValue);
}
}
private void addToHead(Node newValue) {
if(first == null) {
first = newValue;
tail = newValue;
return;
}
if (SIZE == 1) { //只能放一个元素,直接替换
map.remove(tail.k);
tail = newValue;
first = newValue;
return;
}
if (map.size() >= SIZE) {
removeTail();
}
newValue.next = first;
first.pre = newValue;
first = newValue;
}
private void removeTail() {
map.remove(tail.k);
Node pre = tail.pre;
pre.next = null;
tail = pre;
}
}
对于key是自定义结构,我们扩充算法到一般情形
package practise;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.concurrent.locks.ReentrantLock;
public class Cache<K, V> {
public static class Node<V> {
public V value;
public Node<V> last;
public Node<V> next;
public Node(V value) {
this.value = value;
}
}
public static class NodeDoubleLinkedList<V> {
private Node<V> head; //队头
private Node<V> tail; //队尾
public NodeDoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<V> newNode) {
if (newNode == null) {
return;
}
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.last = this.tail;
this.tail = newNode;
}
}
public void moveNodeToTail(Node<V> node) {
if (this.tail == node) {
return;
}
if (this.head == node) {
this.head = node.next;
this.head.last = null;
} else {
node.last.next = node.next;
node.next.last = node.last;
}
node.last = this.tail;
node.next = null;
this.tail.next = node;
this.tail = node;
}
public Node<V> removeHead() {
if (this.head == null) {
return null;
}
Node<V> res = this.head;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = res.next;
res.next = null;
this.head.last = null;
}
return res;
}
}
public static class MyCache<K, V> {
private HashMap<K, Node<V>> keyNodeMap;
private HashMap<Node<V>, K> nodeKeyMap;
private NodeDoubleLinkedList<V> nodeList;
private int capacity;
public MyCache(int capacity) {
if (capacity < 1) {
throw new RuntimeException("should be more than 0.");
}
this.keyNodeMap = new HashMap<K, Node<V>>();
this.nodeKeyMap = new HashMap<Node<V>, K>();
this.nodeList = new NodeDoubleLinkedList<V>();
this.capacity = capacity;
}
public V get(K key) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
this.nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> node = this.keyNodeMap.get(key);
node.value = value;
this.nodeList.moveNodeToTail(node);
} else {
Node<V> newNode = new Node<V>(value);
this.keyNodeMap.put(key, newNode);
this.nodeKeyMap.put(newNode, key);
this.nodeList.addNode(newNode);
if (this.keyNodeMap.size() == this.capacity + 1) {
this.removeMostUnusedCache();
}
}
}
private void removeMostUnusedCache() {
Node<V> removeNode = this.nodeList.removeHead();
K removeKey = this.nodeKeyMap.get(removeNode);
this.nodeKeyMap.remove(removeNode);
this.keyNodeMap.remove(removeKey);
}
}
public static void main(String[] args) {
MyCache<String, Integer> testCache = new MyCache<String, Integer>(3);
testCache.set("A", 1);
testCache.set("B", 2);
testCache.set("C", 3);
System.out.println(testCache.get("B")); // 返回2
System.out.println(testCache.get("A")); // 返回1
testCache.set("D", 4);
System.out.println(testCache.get("D")); // 返回4
System.out.println(testCache.get("C"));// 返回null
System.out.println(testCache.get("A"));// 返回1
}
}