Map + doubly linked list
Time O(1) per operation Space O(capacity)Sentinels head and tail. get: move to front. put: update and move, or insert at front and evict tail.prev if over capacity.
capacity 2: put(1,1), put(2,2), get(1), put(3,3), get(2)map(map)
Step 1/6put(1,1): make a node, store it in the map, and put it at the front of the list.
import java.util.HashMap;
import java.util.Map;
class LRUCache {
private static class Node {
int key, val;
Node prev, next;
Node(int key, int val) { this.key = key; this.val = val; }
}
private final int capacity;
private final Map<Integer, Node> map = new HashMap<>();
private final Node head = new Node(0, 0), tail = new Node(0, 0);
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
Node n = map.get(key);
if (n == null) return -1;
unlink(n);
addFront(n);
return n.val;
}
public void put(int key, int value) {
Node n = map.get(key);
if (n != null) { n.val = value; unlink(n); addFront(n); return; }
n = new Node(key, value);
map.put(key, n);
addFront(n);
if (map.size() > capacity) {
Node lru = tail.prev;
unlink(lru);
map.remove(lru.key);
}
}
private void unlink(Node n) { n.prev.next = n.next; n.next.prev = n.prev; }
private void addFront(Node n) {
n.next = head.next;
n.prev = head;
head.next.prev = n;
head.next = n;
}
}Verdict: The standard answer.