-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLFUCache.java
73 lines (56 loc) · 1.59 KB
/
LFUCache.java
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
import java.util.LinkedHashMap;
import java.util.Map;
/*
* Implementation by Eric Xing: O(1) query, O(N) insertion
* Evicts the data that is least frequently used when cache capacity is met
*/
public class LFUCache implements Cache {
// stores a value and its access frequency
static class Node {
int value;
int frequency;
public Node(int value) {
this.value = value;
this.frequency = 0;
}
}
int capacity;
int count;
// LinkedHashMap to store cache
LinkedHashMap<Integer, Node> cache = new LinkedHashMap<Integer, Node>();
public LFUCache(int capacity) {
this.capacity = capacity;
this.count = 0;
}
public void add(int value) {
if (count != capacity) { // if not full
cache.put(value, new Node(value)); // just add the value in
count++;
} else { // full
cache.remove(getLFU()); // remove the LFU
cache.put(value, new Node(value)); // add the new value in
}
}
public int getLFU() {
int val = -1;
int minFreq = Integer.MAX_VALUE;
// iterate through all entries, and find the LFU
for (Map.Entry<Integer, Node> entry : cache.entrySet()) {
if (minFreq > entry.getValue().frequency) {
val = entry.getKey();
minFreq = entry.getValue().frequency;
}
}
return val; // return LFU value
}
public int get(int value) {
if (cache.containsKey(value)) { // O(1) query, because of HashMap
// increase the frequency by 1 and put it back in the cache:
Node node = cache.remove(value);
node.frequency++;
cache.put(value, node);
return node.value;
}
return -1;
}
}