-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
60 lines (47 loc) · 1.33 KB
/
LRUCache.java
File metadata and controls
60 lines (47 loc) · 1.33 KB
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
package medium;
import java.util.HashMap;
import java.util.LinkedList;
public class LRUCache {
class LRUNode{
int key;
int value;
LRUNode(int key, int value) {
this.key = key;
this.value = value;
}
}
private int capacity;
private LinkedList<LRUNode> queue;
private HashMap<Integer, LRUNode> map;
public LRUCache(int capacity) {
this.capacity = capacity;
this.queue = new LinkedList<>();
this.map = new HashMap<>();
}
public int get(int key) {
if (map.get(key) == null) {
return -1;
}else {
queue.remove(map.get(key));
queue.addFirst(map.get(key));
return map.get(key).value;
}
}
public void put(int key, int value) {
LRUNode newNode = new LRUNode(key, value);
if (map.get(key) == null) {
// 没有数据
if (queue.size() >= this.capacity) {
// 数据量达到上限
LRUNode deleteNode = queue.pollLast();
map.remove(deleteNode.key);
}
queue.addFirst(newNode);
map.put(key, newNode);
}else {
queue.remove(map.get(key));
map.put(key, newNode);
queue.addFirst(newNode);
}
}
}