LRU
1、用Java自带的LinkedHashMap
实现
public class LRUCache {
int capacity;
Map<Integer, Integer> map;
public LRUCache(int capacity) {
this.capacity = capacity;
map = new LinkedHashMap<>((int)((float)capacity / 0.75f + 1.0f), 0.75f, true);
}
public int get(int key) {
Integer value = map.get(key);
if (value == null)
return -1;
return value;
}
public void put(int key, int value) {
map.put(key, value);
if (map.size() > capacity) {
map.remove(map.entrySet().iterator().next().getKey());
}
}
}
2、用双向链表实现
public class LRUCache {
static class Node {
Node pre;
Node next;
int key;
int value;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
Map<Integer, Node> map;
int capacity;
Node head;
Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.head = new Node(-1, -1);
this.tail = new Node(-1, -1);
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node temp = map.get(key);
temp.pre.next = temp.next;
temp.next.pre = temp.pre;
moveToTail(temp);
return temp.value;
}
public void put(int key, int value) {
if (get(key) != -1) {
map.get(key).value = value;
return;
}
Node temp = new Node(key, value);
map.put(key, temp);
moveToTail(temp);
if (map.size() > capacity) {
map.remove(head.next.key);
head.next = head.next.next;
head.next.pre = head;
}
}
public void moveToTail(Node node) {
node.pre = tail.pre;
tail.pre.next = node;
tail.pre = node;
node.next = tail;
}
}
3、单项链表实现
public class LRUCache {
static class Node {
Node next;
int value;
int key;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
Map<Integer, Node> map;
int capacity;
Node head;
Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.head = new Node(-1, -1);
this.tail = head;
}
public int get(int key) {
if (!map.containsKey(key)) return -1;
Node pre = map.get(key);
Node cur = pre.next;
if (cur != tail) {
pre.next = cur.next;
map.put(cur.next.key, pre);
map.put(cur.key, tail);
moveToTail(cur);
}
return cur.value;
}
public void put(int key, int value) {
if (get(key) != -1) {
map.get(key).next.value = value;
return;
}
Node node = new Node(key, value);
map.put(key, tail);
moveToTail(node);
if(map.size() > capacity) {
map.remove(head.next.key);
map.put(head.next.next.key, head);
head.next = head.next.next;
}
}
public void moveToTail(Node node) {
node.next = null;
tail.next = node;
tail = tail.next;
}
}