LRU Cache
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.
思路:map 存key 和指针(指向list中的数据对)。List存(key,value)数据对。
C++ list是用双向链表实现。所以可以实现O(1)删除。
class LRUCache{
public:
struct cacheEntry{
public:
int value;
int key;
cacheEntry(int k,int v):key(k),value(v){}
};
LRUCache(int capacity) {
m_capacity=capacity;
}
int get(int key) {
if(m_map.find(key)==m_map.end())
return -1;
updateEntry(key);
return m_map[key]->value;
}
void set(int key, int value) {
if(m_map.find(key)==m_map.end())
{
cacheEntry newItem(key,value);
if(m_LRU_cache.size()>=m_capacity)
{
m_map.erase(m_LRU_cache.back().key);//!!important!!
m_LRU_cache.pop_back();
}
m_LRU_cache.push_front(newItem);
m_map[key]=m_LRU_cache.begin();
return;
}
m_map[key]->value=value;
updateEntry(key);
}
private:
int m_capacity;
list<cacheEntry> m_LRU_cache;
unordered_map<int,list<cacheEntry>::iterator> m_map;
void updateEntry(int key)
{
auto item=*m_map[key];
m_LRU_cache.erase(m_map[key]);
m_LRU_cache.push_front(item);
m_map[key]=m_LRU_cache.begin();
}
};
浙公网安备 33010602011771号