Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Solution:
class LRUCache{
private:
int capacity;
list<int> LRU;
unordered_map<int, int> mv;
unordered_map<int, list<int>::iterator> mp;
public:
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
unordered_map<int, list<int>::iterator>::iterator iter = mp.find(key);
if(iter != mp.end())
{
LRU.erase(mp[key]);
LRU.push_front(key);
mp[key] = LRU.begin();
return mv[key];
}
else return -1;
}
void set(int key, int value) {
unordered_map<int, list<int>::iterator>::iterator iter = mp.find(key);
if(iter == mp.end())
{
if(LRU.size() == capacity)
{
mp.erase(LRU.back());
LRU.pop_back();
}
}
else LRU.erase(mp[key]);
LRU.push_front(key);
mv[key] = value;
mp[key] = LRU.begin();
}
};
设计与实现LRU缓存的数据结构
925

被折叠的 条评论
为什么被折叠?



