-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path460.cpp
More file actions
executable file
·75 lines (60 loc) · 1.83 KB
/
460.cpp
File metadata and controls
executable file
·75 lines (60 loc) · 1.83 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
class LFUCache {
private:
unordered_map<int, int> KV;
unordered_map<int, list<int>> freqK;
unordered_map<int, int> kFreq;
unordered_map<int, list<int>::iterator> kFreqIt;
int cap;
int minimumFreq;
public:
LFUCache(int capacity) {
this->cap = capacity;
minimumFreq = INT_MAX;
}
int get(int key) {
if (this->cap == 0){
return -1;
}
if (KV.count(key)){
int freq = kFreq[key];
kFreq[key] = freq + 1;
freqK[freq].erase(kFreqIt[key]);
freqK[freq + 1].push_front(key);
kFreqIt[key] = freqK[freq + 1].begin();
if (freqK[freq].empty() && minimumFreq == freq){
minimumFreq = freq + 1;
}
return KV[key];
}
return -1;
}
void put(int key, int value) {
if (KV.count(key)){
KV[key] = value;
int freq = kFreq[key];
kFreq[key] = freq + 1;
freqK[freq].erase(kFreqIt[key]);
freqK[freq + 1].push_front(key);
kFreqIt[key] = freqK[freq + 1].begin();
if (freqK[freq].empty() && minimumFreq == freq){
minimumFreq = freq + 1;
}
return;
}
if (this->cap == 0){
return;
}
if (KV.size() == cap){
int invK = freqK[minimumFreq].back();
KV.erase(invK);
freqK[minimumFreq].erase(kFreqIt[invK]);
kFreqIt.erase(invK);
kFreq.erase(invK);
}
KV[key] = value;
freqK[1].push_front(key);
kFreq[key] = 1;
kFreqIt[key] = freqK[1].begin();
minimumFreq = 1;
}
};