-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlfu.cpp
More file actions
86 lines (61 loc) · 1.8 KB
/
lfu.cpp
File metadata and controls
86 lines (61 loc) · 1.8 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
76
77
78
79
80
81
82
83
84
85
86
#include<algorithm>
#include <unordered_map>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
class LFUCache {
public:
unordered_map<int, list<int>> freq_keyslist;
unordered_map<int, vector<int>> key_value_freq;
unordered_map<int, list<int>::iterator> key_iterator;
int min_freq;
int size;
int c;
LFUCache(int capacity) {
c = capacity;
size = 0;
min_freq = 0;
}
int get(int key) {
if(!key_value_freq.count(key)) return -1;
int value = key_value_freq[key][0];
int freq = key_value_freq[key][1];
freq_keyslist[freq].erase(key_iterator[key]);
freq_keyslist[freq+1].push_back(key);
key_value_freq[key][1]++;
key_iterator[key] = --freq_keyslist[freq+1].end();
if(!freq_keyslist[min_freq].size()) min_freq++;
return value;
}
void put(int key, int value) {
if(c<=0) return;
if(get(key) != -1){
key_value_freq[key][0] = value;
return;
}
if(size==c){
int key_to_remove = freq_keyslist[min_freq].front();
freq_keyslist[min_freq].pop_front();
key_value_freq.erase(key_to_remove);
key_iterator.erase(key_to_remove);
}
key_value_freq[key] = {value, 1};
freq_keyslist[1].push_back(key);
key_iterator[key] = --freq_keyslist[1].end();
min_freq=1;
if(size < c) size++;
}
};
int main() {
LFUCache cache = *new LFUCache( 2 );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);
cache.put(3, 3);
cache.get(2);
cache.put(4, 4);
cache.get(1);
cache.get(3);
cache.get(4);
}