Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
lfu-cache.cpp 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-08-27 15:44 +08:00 . Update lfu-cache.cpp
// Time: O(1), per operation
// Space: O(k), k is the capacity of cache
class LFUCache {
public:
LFUCache(int capacity) : capa_(capacity), size_(0), min_freq_(0) {
}
int get(int key) {
if (!key_to_nodeit_.count(key)) {
return -1;
}
auto new_node = *key_to_nodeit_[key];
auto& freq = std::get<FREQ>(new_node);
freq_to_nodes_[freq].erase(key_to_nodeit_[key]);
if (freq_to_nodes_[freq].empty()) {
freq_to_nodes_.erase(freq);
if (min_freq_ == freq) {
++min_freq_;
}
}
++freq;
freq_to_nodes_[freq].emplace_back(move(new_node));
key_to_nodeit_[key] = prev(freq_to_nodes_[freq].end());
return std::get<VAL>(*key_to_nodeit_[key]);
}
void put(int key, int value) {
if (capa_ <= 0) {
return;
}
if (get(key) != -1) {
std::get<VAL>(*key_to_nodeit_[key]) = value;
return;
}
if (size_ == capa_) {
key_to_nodeit_.erase(std::get<KEY>(freq_to_nodes_[min_freq_].front()));
freq_to_nodes_[min_freq_].pop_front();
if (freq_to_nodes_[min_freq_].empty()) {
freq_to_nodes_.erase(min_freq_);
}
--size_;
}
min_freq_ = 1;
freq_to_nodes_[min_freq_].emplace_back(key, value, min_freq_);
key_to_nodeit_[key] = prev(freq_to_nodes_[min_freq_].end());
++size_;
}
private:
enum Data {KEY, VAL, FREQ};
int capa_;
int size_;
int min_freq_;
unordered_map<int, list<tuple<int, int, int>>> freq_to_nodes_; // freq to list of {key, val, freq}
unordered_map<int, list<tuple<int, int, int>>::iterator> key_to_nodeit_; // key to list iterator
};
/**
* 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);
*/
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助