-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path29_lfucache.cpp
More file actions
63 lines (52 loc) · 1.45 KB
/
29_lfucache.cpp
File metadata and controls
63 lines (52 loc) · 1.45 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
//https://leetcode.com/problems/lfu-cache/description/
class LFUCache {
private:
int cap;
int size;
int minFreq;
unordered_map<int, pair<int, int>> m; //key to {value,freq};
unordered_map<int, list<int>::iterator> mIter; //key to list iterator;
unordered_map<int, list<int>> fm; //freq to key list;
public:
LFUCache(int capacity) {
cap=capacity;
size=0;
}
int get(int key) {
if(m.count(key)==0) return -1;
fm[m[key].second].erase(mIter[key]);
m[key].second++;
fm[m[key].second].push_back(key);
mIter[key]=--fm[m[key].second].end();
if(fm[minFreq].size()==0 )
minFreq++;
return m[key].first;
}
void put(int key, int value) {
if(cap<=0) return;
int storedValue=get(key);
if(storedValue!=-1)
{
m[key].first=value;
return;
}
if(size>=cap )
{
m.erase( fm[minFreq].front() );
mIter.erase( fm[minFreq].front() );
fm[minFreq].pop_front();
size--;
}
m[key]={value, 1};
fm[1].push_back(key);
mIter[key]=--fm[1].end();
minFreq=1;
size++;
}
};
/**
* 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);
*/