leetcode 460. LFU 缓存 hard
题目描述:
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。
实现 LFUCache 类:
LFUCache(int capacity) - 用数据结构的容量 capacity 初始化对象
int get(int key) - 如果键存在于缓存中,则获取键的值,否则返回 -1。
void put(int key, int value) - 如果键已存在,则变更其值;如果键不存在,请插入键值对。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近最久未使用 的键。
注意「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0 。
为了确定最不常使用的键,可以为缓存中的每个键维护一个 使用计数器 。使用计数最小的键是最久未使用的键。
当一个键首次插入到缓存中时,它的使用计数器被设置为 1 (由于 put 操作)。对缓存中的键执行 get 或 put 操作,使用计数器的值将会递增。
解题思路:
两个hash表
代码:
struct Node{
int key, val, times;
Node(int key, int val, int times):key(key), val(val), times(times) {}
};
class LFUCache {
public:
LFUCache(int capacity): cap(capacity), min_times(0){}
int get(int key) {
if (cap == 0)
return -1;
// 如果找到了, 更新访问次数,并且更新最少访问次数
if (key_2_it.count(key))
{
// 找到旧的 Node, 删之
auto it = key_2_it[key];
int times = it->times;
int val = it->val;
times_2_list[times].erase(it);
// 如果当前链表为空,我们需要在哈希表中删除,且更新min_times
if (times_2_list[times].empty())
{
times_2_list.erase(times);
if (times == min_times)
min_times = times+1;
}
times_2_list[times+1].emplace_front(key, val, times+1);
key_2_it[key] = times_2_list[times+1].begin();
return val;
}
return -1;
}
void put(int key, int value) {
if (cap == 0)
return;
if (key_2_it.count(key))
{
auto it = key_2_it[key];
int times = it->times;
times_2_list[times].erase(it);
if (times_2_list[times].empty())
{
times_2_list.erase(times);
if (times == min_times)
min_times = times+1;
}
times_2_list[times+1].emplace_front(key, value, times+1);
key_2_it[key] = times_2_list[times+1].begin();
}
else
{
// 如果要插入, 且size超了, 那先删除最近最久未使用的
if (key_2_it.size() == cap)
{
int key = times_2_list[min_times].back().key;
key_2_it.erase(key);
times_2_list[min_times].pop_back();
if (times_2_list[min_times].empty())
{
times_2_list.erase(min_times);
}
}
times_2_list[1].emplace_front(key, value, 1);
key_2_it[key] = times_2_list[1].begin();
min_times = 1;
}
}
private:
int cap;
int min_times;
unordered_map<int, list<Node>::iterator> key_2_it;
unordered_map<int, list<Node>> times_2_list;
};
/**
* 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);
*/