stl
#include <iostream>
#include <list>
#include <unordered_map>
class LRUCache {
std::list<std::pair<int, int>> res;
std::unordered_map<int, std::list<std::pair<int, int>>::iterator> umap;
int cap;
public:
LRUCache(int capacity) :cap(capacity) {
}
int get(int key) {
if (umap.find(key) == umap.end()) {
return -1;
}
std::pair<int, int> node = *umap[key];
res.erase(umap[key]);
res.push_front(node);
umap[key] = res.begin();
return node.second;
}
void put(int key, int value) {
auto node = std::make_pair(key, value);
if (umap.count(key)) {
res.erase(umap[key]);
}
else if (umap.size() == cap) {
umap.erase(res.back().first);
res.pop_back();
}
res.push_front(node);
umap[key] = res.begin();
}
};
int main()
{
}
链表
//待补充