-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path460.cpp
70 lines (66 loc) · 1.76 KB
/
460.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
class LFUCache {
// Runtime: 108 ms, faster than 97.00% of C++ online submissions for LFU
// Cache. Memory Usage: 40.3 MB, less than 75.85% of C++ online submissions
// for LFU Cache.
int cap;
int minFreq;
using L = list<tuple<int, int, int>>; // k,v,count
unordered_map<int, L> count2kv;
unordered_map<int, L::iterator> hashmap;
public:
LFUCache(int capacity) : cap(capacity), minFreq(0) {}
int get(int key) {
auto it = hashmap.find(key);
if (it == end(hashmap))
return -1;
auto [k, v, c] = *it->second;
{
auto &target = count2kv[c];
target.erase(it->second);
if (target.size() == 0 and minFreq == c)
++minFreq;
}
{
auto &target = count2kv[c + 1];
target.emplace_front(k, v, c + 1);
it->second = target.begin();
}
return v;
}
void put(int key, int value) {
if (cap == 0)
return;
auto it = hashmap.find(key);
if (it == end(hashmap)) {
if (hashmap.size() >= cap) {
auto &target = count2kv[minFreq];
auto [k, v, c] = target.back();
hashmap.erase(k);
target.pop_back();
}
auto &target = count2kv[1];
target.emplace_front(key, value, 1);
hashmap[key] = target.begin();
minFreq = 1;
} else {
auto [k, v, c] = *it->second;
{
auto &target = count2kv[c];
target.erase(it->second);
if (target.size() == 0 and minFreq == c)
++minFreq;
}
{
auto &target = count2kv[c + 1];
target.emplace_front(key, value, c + 1);
it->second = target.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);
*/