Design a data structure that follows the constraints of a Least Recently Used(LRU) cache.
Implement the LRUCache
class:
LRUCache(int capacity)
Initialize the LRU cache with positive size capacity.int get(int key)
Return the value of the key if the key exists, otherwise return -1.void put(int key, int value)
Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.
The functions get and put must each run in \(O(1)\) average time complexity.
Solution
我们用 \(list\) 套 \(pair\) 来表示 \(LRU\), 这样我们可以方便的进行插入和删除。
对于 \(cache\), 我们用 \(unordered\_map\) 来表示,映射 \(key\) 到 \(list[pair]\).
点击查看代码
class LRUCache {
private:
list<pair<int,int>> lru;
unordered_map<int,list<pair<int,int>>::iterator> cache;
int cap;
public:
LRUCache(int capacity) {
this->cap = capacity;
}
int get(int key) {
if(cache.find(key)==cache.end())return -1;
auto ele = cache[key];
int val = (*ele).second;
lru.erase(ele);
cache[key] = lru.insert(lru.end(), {key,val});
return val;
}
void put(int key, int value) {
if(cache.find(key)==cache.end()){
if(cap==lru.size()){
cache.erase(lru.front().first);
lru.pop_front();
}
}
else{
lru.erase(cache[key]);
}
cache[key]=lru.insert(lru.end(),{key,value});
}
};
/**
* 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);
*/