思路
- 如果缓存中的值被访问就移到最前面
- 如果缓存满了,仍在添加值,那么移除尾部的值,然后再添加值到头部
- 使用哈希表+链表实现
Code
public class Node<V> {
String key;
V value;
Node<V> prev;
Node<V> next;
public Node() {
}
public Node(String key, V value) {
this.key = key;
this.value = value;
}
}
public class LruCache<V> {
private int initialCapacity = 1024;
private Map<String, Node<V>> cache = new HashMap<>();
private Node<V> head;
private Node<V> tail;
public LruCache() {
head = new Node<>();
tail = new Node<>();
head.next = tail;
tail.prev = head;
}
public LruCache(int initialCapacity) {
this();
this.initialCapacity = initialCapacity;
}
public V get(String key) {
Node<V> node = cache.get(key);
if (null == node) {
return null;
}
moveToHead(node);
return node.value;
}
public void put(String key, V value) {
Node<V> node = cache.get(key);
if (null != node) {
node.value = value;
moveToHead(node);
return;
}
if (cache.size() == initialCapacity) {
Node<V> tail = removeTail();
cache.remove(tail.key);
}
Node<V> resultNode = new Node<>(key, value);
cache.put(key, resultNode);
addHead(resultNode);
}
private void remove(Node<V> node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void addHead(Node<V> node) {
node.next = head.next;
node.prev = head;
head.next.prev = node;
head.next = node;
}
private void moveToHead(Node<V> node) {
remove(node);
addHead(node);
}
private Node<V> removeTail() {
Node<V> node = tail.prev;
remove(node);
return node;
}
}
时间复杂度:O(1)
空间复杂度:O(1)
|