-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path460. LFU Cache.cpp
86 lines (61 loc) · 1.84 KB
/
460. LFU Cache.cpp
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
82
83
84
85
86
class LFUCache {
int n;
int minfreq;
// key, value, freq
unordered_map<int, pair<int, int> > db;
// key
unordered_map<int, list<int>::iterator > itcache;
// freq, list->key
unordered_map<int, list<int>> cache;
public:
LFUCache(int capacity) {
n = capacity;
}
int get(int key) {
auto it = db.find(key);
auto iter = itcache.find(key);
if(it == db.end() || iter == itcache.end())
return -1;
(it->second.second)++;
int newfreq = it->second.second;
int curfreq = newfreq-1;
cache[curfreq].erase(iter->second);
cache[newfreq].push_front(key);
itcache[key] = cache[newfreq].begin();
if(cache[minfreq].size() == 0)
minfreq++;
return it->second.first;
}
void put(int key, int value) {
auto it = db.find(key);
auto iter = itcache.find(key);
if(it!=db.end()) {
(it->second.second)++;
it->second.first = value;
int newfreq = it->second.second;
int curfreq = newfreq-1;
cache[curfreq].erase(iter->second);
cache[newfreq].push_front(key);
itcache[key] = cache[newfreq].begin();
return;
}
if(itcache.size() == n) {
if(cache[minfreq].size() == 0)
return;
int keytodel = cache[minfreq].back();
cache[minfreq].pop_back();
itcache.erase(keytodel);
db.erase(keytodel);
}
minfreq = 1;
db[key] = make_pair(value, 1);
cache[1].push_front(key);
itcache[key] = cache[1].begin();
}
};
/**
* 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);
*/