题目描述
请你为 最不经常使用(LFU)缓存算法设计并实现数据结构。它应该支持以下操作:get 和 put。
get(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。
put(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,则应该在插入新项之前,使最不经常使用的项无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,应该去除 最近 最少使用的键。
「项的使用次数」就是自插入该项以来对其调用 get 和 put 函数的次数之和。使用次数会在对应项被移除后置为 0
案例
LFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 去除 key 2
cache.get(2); // 返回 -1 (未找到key 2)
cache.get(3); // 返回 3
cache.put(4, 4); // 去除 key 1
cache.get(1); // 返回 -1 (未找到 key 1)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
代码(在本地可以运行成功,但是lettcode上不行)
class LFUCache {
public:
LFUCache(int capacity) {
cacheCapacity = capacity;
}
int get(int key) {
int data = cacheData[key].first;
if (data == 0) {//删除自动加在map中的元素
unordered_map<int, pair<int, int>>::iterator it = cacheData.find(key);
cacheData.erase(it);
return -1;
}
else {
cacheData[key].second++;
int frequency = cacheData[key].second;
//删除之前在频率表中的数据
unordered_map<int, int>::iterator it = mapData[frequency - 1].find(key);
mapData[frequency - 1].erase(it);
if (mapData[frequency - 1].size() == 0) {//删除元素
map<int, unordered_map<int, int>>::iterator itMy = mapData.find(frequency - 1);
mapData.erase(itMy);
}
//加入新的频率表中
mapData[frequency][key] = 0;
return cacheData[key].first;
}
}
void put(int key, int value) {
if (cacheData.size() == cacheCapacity) {//删除操作
/*int index = mapData[0].size() - 1;*/
unordered_map<int, int>::iterator it = mapData.begin()->second.begin();
//it--;
int cacheKey = it->first;//获得要删除的元素的Key
mapData.begin()->second.erase(it);
if (mapData.begin()->second.size() == 0) {//删除元素
map<int, unordered_map<int, int>>::iterator itMy = mapData.begin();
mapData.erase(itMy);
}
//删除元素
unordered_map<int, pair<int, int>>::iterator itm = cacheData.find(cacheKey);
cacheData.erase(itm);
}
cacheData[key] = { value,0 };
mapData[0][key] = value;//增加到频率数组中
}
private:
int cacheCapacity;
unordered_map<int,pair<int,int>> cacheData;
map<int,unordered_map<int,int>> mapData;
};