leetcode146

长度固定的缓存,当超出长度,使最长时间不使用的对象失效.

思路:hashMap+双向链表

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.HashMap;
import java.util.Map;

class LRUCache {
private LRUNode head;
private LRUNode tail;
private Map<Integer,LRUNode> map;
private int capacity;
private int len = 0;
public LRUCache(int capacity) {
map = new HashMap<Integer,LRUNode>(capacity);
this.capacity = capacity;
}
public int get(int key) {
LRUNode node = map.get(key);
if (node!=null){
removeNode(node);
addNodeToHead(node);
return node.value;
}
return -1;
}
public void put(int key, int value) {
LRUNode node = map.get(key);
if (node==null){
len++;
if (len>capacity){
map.remove(tail.key);
removeTail();
len--;
}
node = new LRUNode(key,value);
addNodeToHead(node);
map.put(key,node);
}else{
node.value = value;
removeNode(node);
addNodeToHead(node);
}
}
private void addNodeToHead(LRUNode node){
node.next = head;
node.pre = null;
if (head!=null){
head.pre = node;
}
head = node;
if (tail==null){
tail = node;
}
}

private void removeTail(){
if (tail!=null){
LRUNode pre = tail.pre;
if (pre!=null){
pre.next = null;
tail = pre;
}else{
//说明是head节点
head = null;
}
}
}

private void removeNode(LRUNode node){
LRUNode pre = node.pre;
LRUNode next = node.next;
if (pre!=null){
pre.next = next;
}else{
head = next;
}
if (next!=null){
next.pre = pre;
}else{
tail = pre;
}
}
private class LRUNode{
int key;
int value;
LRUNode next;
LRUNode pre;
public LRUNode(int key,int value){
this.key = key;
this.value = value;
}
}
}