哈希表+雙鏈表import java.util.Map;
import java.util.HashMap;
class DLink {
protected int key;
protected int value;
protected DLink pre;
protected DLink next;
public DLink() {
this.key = 0;
this.value = 0;
this.pre = null;
this.next = null;
}
public DLink(int key, int value) {
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
public class LRUCache {
private int capacity;
private DLink head, tail;
private Map<Integer, DLink> Lt = new HashMap<Integer, DLink>();
public LRUCache(int capacity) {
this.capacity = capacity;
head = new DLink();
tail = new DLink();
head.next = tail;
tail.pre = head;
}
public int get(int key) {
DLink node = this.Lt.get(key);
if (node == null) return -1;
else {
node.pre.next = node.next;
node.next.pre = node.pre;
node.pre = tail.pre;
node.next = tail;
node.pre.next = node;
tail.pre = node;
return node.value;
}
}
public void put(int key, int value) {
DLink node = this.Lt.get(key);
if (node == null) {
node = new DLink(key, value);
if (this.Lt.size() < this.capacity) {
node.pre = tail.pre;
node.next = tail;
node.pre.next = node;
tail.pre = node;
Lt.put(key, node);
} else {
Lt.remove(head.next.key);
head.next.next.pre = head;
head.next = head.next.next;
node.pre = tail.pre;
node.next = tail;
node.pre.next = node;
tail.pre = node;
Lt.put(key, node);
}
} else {
node.value = value;
node.pre.next = node.next;
node.next.pre = node.pre;
node.pre = tail.pre;
node.next = tail;
node.pre.next = node;
tail.pre = node;
}
}
}