0%

LRU Cache

用hashmap和双向链表实现的LRU.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class LRUCache {
Map<Integer, DListNode> map;
DListNode head;
DListNode tail;
int cap;
public LRUCache(int capacity) {
cap = capacity;
map = new HashMap<>();
head = new DListNode(0,0);
tail = new DListNode(0,0);
head.next = tail;
tail.prev = head;
}

public int get(int key) {
if (!map.containsKey(key)) {
return -1;
}
DListNode listNode = map.get(key);
remove(listNode);
addHead(listNode);
return listNode.val;
}

public void put(int key, int value) {
if (map.containsKey(key)) {
DListNode listNode = map.get(key);
listNode.val = value;
remove(listNode);
addHead(listNode);
} else {
DListNode listNode = new DListNode(key, value);
addHead(listNode);
if (map.size() == cap) {
map.remove(tail.prev.key);
remove(tail.prev);
}
map.put(key, listNode);
}
}

private void remove(DListNode node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}

private void addHead(DListNode listNode) {
DListNode tmp = head.next;
head.next = listNode;
listNode.next = tmp;
tmp.prev = listNode;
listNode.prev = head;
}
}

class DListNode {
int key;
int val;
DListNode next;
DListNode prev;
public DListNode(int k, int v) {
key = k;
val = v;
}
}