# LeetCode题解：LRU Cache

1551人阅读 评论(2)

### 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.

class LRUCache
{
int m_Capacity;
unordered_map<int, int> m_Cache;
list<int> m_Recently;

void touch(int key)
{
auto kiter = find(begin(m_Recently), end(m_Recently), key);
m_Recently.erase(kiter);
m_Recently.push_front (key);
}
public:
LRUCache (int capacity) : m_Capacity (capacity)
{}

int get (int key)
{
auto iter = m_Cache.find (key);
if (iter == end(m_Cache))
else
{
touch(key);
return iter->second;
}
}

void set (int key, int value)
{
auto iter = m_Cache.find (key);

if (iter == end(m_Cache))
{
if  (m_Cache.size() >= m_Capacity)
{
int last = m_Recently.back();
m_Recently.pop_back();
m_Cache.erase (last);
}
m_Recently.push_front(key);
}

m_Cache[key] = value;
touch(key);
}
};


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：192166次
• 积分：3562
• 等级：
• 排名：第9202名
• 原创：152篇
• 转载：0篇
• 译文：1篇
• 评论：28条
阅读排行
最新评论