-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek 7 460. LFU Cache
66 lines (55 loc) · 1.69 KB
/
week 7 460. LFU Cache
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
public class LFUCache {
HashMap<Integer, Integer> vals; // store key --value
HashMap<Integer, Integer> freqs; // store frequency
HashMap<Integer, LinkedHashSet<Integer>> Lists; // store freq -- key
int capacity;
int minFreq = 1;
public LFUCache(int capacity) {
this.capacity = capacity;
this.vals = new HashMap<>();
this.freqs = new HashMap<>();
this.lists = new HashMap<>();
this.lists.put(1, new LinkedHashSet<>());
}
public int get(int key) {
if (!vals.containsKey(key)){
return -1;
}
int freq = freqs.get(key);
freqs.put(key, freq + 1);
lists.get(freq).remove(key);
if(freq == minFreq && lists.get(freq).size() == 0){
minFreq++;
}
if(!lists.containsKey(freq + 1)){
lists.put(freq + 1, new LinkedHashSet<>());
}
lists.get(freq + 1).add(key);
return vals.get(key);
}
public void put(int key, int value) {
if(this.capacity <= 0){
return;
}
if(vals.containsKey(key)){
vals.put(key, value);
get(key);
return;
}
if(vals.size() >= this.capacity){
int evit = lists.get(minFreq).iterator().next();
lists.get(minFreq).remove(evit);
vals.remove(evit);
}
vals.put(key, value);
freqs.put(key, 1);
minFreq = 1;
lists.get(1).add(key);
}
}
/**
* 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);
*/