面试题 16.25
Solutions
class LRUCache {
public:
using kv = pair<int, int>;
int cap = 0;
list<kv> lru;
unordered_map<int, list<kv>::iterator> m;
LRUCache(int capacity) : cap(capacity) {
}
int get(int key) {
if (!m.count(key))
return -1;
else {
update(key, m[key]->second);
return m[key]->second;
}
}
void put(int key, int value) {
if (lru.size() >= cap && !m.count(key))
evict();
update(key, value);
}
void evict() {
if (lru.size()) {
m.erase(lru.back().first);
lru.pop_back();
}
}
void update(int key, int value) {
if (m.count(key))
lru.erase(m[key]);
lru.emplace_front(key, value);
m[key] = lru.begin();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/Last updated