Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
lru-cache.cpp 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-09-21 20:34 +08:00 . Update lru-cache.cpp
// Time: O(1), per operation.
// Space: O(k), k is the capacity of cache.
#include <list>
class LRUCache {
public:
LRUCache(int capacity) : capa_(capacity) {
}
int get(int key) {
if (map_.find(key) != map_.end()) {
// It key exists, update it.
const auto value = map_[key]->second;
update(key, value);
return value;
} else {
return -1;
}
}
void put(int key, int value) {
// If cache is full while inserting, remove the last one.
if (map_.find(key) == map_.end() && list_.size() == capa_) {
auto del = list_.back(); list_.pop_back();
map_.erase(del.first);
}
update(key, value);
}
private:
list<pair<int, int>> list_; // key, value
unordered_map<int, list<pair<int, int>>::iterator> map_; // key, list iterator
int capa_;
// Update (key, iterator of (key, value)) pair
void update(int key, int value) {
auto it = map_.find(key);
if (it != map_.end()) {
list_.erase(it->second);
}
list_.emplace_front(key, value);
map_[key] = list_.begin();
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助