-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0460.cpp
More file actions
executable file
·60 lines (54 loc) · 1.36 KB
/
LC0460.cpp
File metadata and controls
executable file
·60 lines (54 loc) · 1.36 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
/*
Problem Statement: https://leetcode.com/problems/lfu-cache/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|--------------------|------|-------|
| Operations | Time | Space |
|--------------------|------|-------|
| LFUCache(capacity) | O(1) | O(1) |
| get(key) | O(1) | O(1) |
| put(key, value) | O(1) | O(1) |
|--------------------|------|-------|
*/
class LFUCache {
private:
class Node {
public:
int key, val, freq;
Node(int key, int val) : key(key), val(val), freq(0) {}
};
int min_freq, capacity;
list<Node> cache;
unordered_map<int, list<Node>> freq;
unordered_map<int, list<Node>::iterator> m;
public:
LFUCache(int capacity) : min_freq(0), capacity(capacity) {}
int get(int key) {
if (!m.count(key))
return -1;
Node node = *m[key];
freq[node.freq].erase(m[key]);
if (node.freq == min_freq && freq[node.freq].size() == 0)
min_freq++;
freq[++node.freq].push_front(node);
m[key] = freq[node.freq].begin();
return node.val;
}
void put(int key, int value) {
if (capacity == 0)
return;
else if (m.count(key)) {
m[key]->val = value;
get(key);
return;
}
Node node(key, value);
freq[node.freq].push_front(node);
m[key] = freq[node.freq].begin();
if (m.size() > capacity) {
m.erase(freq[min_freq].back().key);
freq[min_freq].pop_back();
}
min_freq = node.freq;
}
};