-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFUCache.java
More file actions
76 lines (66 loc) · 2.18 KB
/
Copy pathLFUCache.java
File metadata and controls
76 lines (66 loc) · 2.18 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package leetcode.hard.page2;
import java.util.*;
public class LFUCache {
// <Key, Value>
HashMap<Integer, Integer> vals;
// <Key, Counts>
HashMap<Integer, Integer> counts;
// <Counts, Key LinkedList>
HashMap<Integer, LinkedHashSet<Integer>> order;
int capacity;
int min = 1;
public LFUCache(int capacity) {
this.capacity = capacity;
vals = new HashMap<>();
counts = new HashMap<>();
order = new HashMap<>();
order.put(1, new LinkedHashSet<>());
}
public int get(int key) {
if (!vals.containsKey(key)) return -1;
int oldCount = counts.get(key);
counts.put(key, oldCount + 1);
order.get(oldCount).remove(key);
if (oldCount == min && order.get(oldCount).size() == 0) {
min = oldCount + 1;
}
if (!order.containsKey(oldCount + 1)) {
order.put(oldCount + 1, new LinkedHashSet<>());
}
order.get(oldCount + 1).add(key);
return vals.get(key);
}
public void put(int key, int value) {
if (capacity == 0) return;
if (vals.containsKey(key) || vals.size() < capacity) {
vals.put(key, value);
int oldCount = counts.getOrDefault(key, 0);
counts.put(key, oldCount + 1);
if (!order.containsKey(oldCount + 1)) {
order.put(oldCount + 1, new LinkedHashSet<>());
}
order.get(oldCount + 1).add(key);
if (oldCount == 0) {
min = 1;
} else {
order.get(oldCount).remove(key);
if (oldCount == min && order.get(oldCount).size() == 0) {
min = oldCount + 1;
}
}
} else {
// evict
int removeKey = order.get(min).iterator().next();
vals.remove(removeKey);
counts.remove(removeKey);
order.get(min).remove(removeKey);
min = 1;
vals.put(key, value);
counts.put(key, min);
if (!order.containsKey(min)) {
order.put(min, new LinkedHashSet<>());
}
order.get(min).add(key);
}
}
}