-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathLFU.cpp
More file actions
73 lines (61 loc) · 1.73 KB
/
LFU.cpp
File metadata and controls
73 lines (61 loc) · 1.73 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
class LFUCache {
public:
int cap;
int minfreq = 0;
unordered_map<int, int> cacheKeyFreq;
unordered_map<int, list<pair<int, int> > > frqList;
unordered_map<int, list<pair<int, int> >::iterator > keyAddr;
LFUCache(int capacity) {
cap = capacity;
}
void add(int key, int value, int freq) {
cacheKeyFreq[key] += 1;
auto it = frqList[freq].insert(frqList[freq].end(), {key, value});
keyAddr[key] = it;
}
void updateMinFreq() {
if(frqList[minfreq].size() == 0)
{
frqList.erase(minfreq);
minfreq += 1; // it will always be increased to plus one
}
}
void remove(int key, int freq) {
auto it = keyAddr[key];
frqList[freq].erase(it);
keyAddr.erase(key);
updateMinFreq();
}
void evict() {
auto minEleIt = frqList[minfreq].begin();
int key = minEleIt->first;
remove(key, minfreq);
cacheKeyFreq.erase(key);
}
int get(int key) {
if(cacheKeyFreq.count(key) > 0)
{
int freq = cacheKeyFreq[key];
int value = keyAddr[key]->second;
remove(key, freq);
add(key, value, freq + 1);
return value;
}
return -1;
}
void put(int key, int value) {
if(cap == 0)
return;
if(cacheKeyFreq.count(key) == 0)
{
if(cap == cacheKeyFreq.size())
evict();
minfreq = 1;
add(key, value, minfreq);
return;
}
int lastFreq = cacheKeyFreq[key];
remove(key, lastFreq);
add(key, value, lastFreq + 1);
}
};