forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFU Cache.java
More file actions
81 lines (68 loc) · 2.2 KB
/
LFU Cache.java
File metadata and controls
81 lines (68 loc) · 2.2 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
77
78
79
80
81
class LFUCache {
private Map<Integer, Integer> valMap;
private Map<Integer, Integer> freqMap;
private Map<Integer, LinkedHashSet<Integer>> freqCountMap;
private int capacity;
private int minValue;
public LFUCache(int capacity) {
valMap = new HashMap<>();
freqMap = new HashMap<>();
freqCountMap = new HashMap<>();
this.capacity = capacity;
minValue = 0;
}
public int get(int key) {
if (!valMap.containsKey(key)) {
return -1;
}
// Updating frequency
int oldFreq = freqMap.get(key);
freqMap.put(key, oldFreq + 1);
int newFreq = freqMap.get(key);
// Removing from old frequency set
LinkedHashSet<Integer> set = freqCountMap.get(oldFreq);
set.remove(key);
if (set.isEmpty()) {
// As this was the only key with min freq so minimum frequency should be updated
if (minValue == oldFreq) {
minValue = oldFreq + 1;
}
freqCountMap.remove(oldFreq);
}
else {
freqCountMap.put(oldFreq, set);
}
// Updating new frequency set
freqCountMap.computeIfAbsent(newFreq, k -> new LinkedHashSet<>()).add(key);
return valMap.get(key);
}
public void put(int key, int value) {
if (capacity == 0) {
return;
}
if (get(key) != -1) {
valMap.put(key, value);
return;
}
if (valMap.size() == capacity) {
LinkedHashSet<Integer> set = freqCountMap.get(minValue);
int keyToBeDeleted = set.iterator().next();
valMap.remove(keyToBeDeleted);
freqMap.remove(keyToBeDeleted);
set.remove(keyToBeDeleted);
if (set.isEmpty()) {
freqCountMap.remove(minValue);
}
}
valMap.put(key, value);
freqMap.put(key, 1);
freqCountMap.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key);
minValue = 1;
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/