LeetCode LRU Cache

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

题目大意是要实现最近最久未使用算法。
解题思路:哈希表+链表。用哈希表保存key和value的映射,链表保存访问的cache序列,哈希表用map(或者unsorted_map)实现,每个key对应的value是节点在链表的迭代器;这样,每当访问某个key,就把其设置成链表的队尾,即:队尾就是最近访问的节点,队首就是最远访问的节点。

class LRUCache{

	struct node
	{
		int key, val;
		node(int k, int v)
		{
			key = k;
			val = v;
		}
	};

	typedef list<node> List;
	//map的value是链表节点的迭代器
	typedef map<int, List::iterator> Map;

	int m_capacity;
	List m_list;
	Map m_map;

public:
	//更新链表访问序列,把it移到队列末尾(在队尾生成一个和it一样的节点,再删除原来的节点)
	List::iterator update(List::iterator it)
	{
		List::iterator new_it = m_list.insert(m_list.end(), *it);
		m_list.erase(it);
		return new_it;
	}

	LRUCache(int capacity) {
		m_capacity = capacity;
	}

	int get(int key) {
		Map::iterator it = m_map.find(key);
		if (it == m_map.end())
			return -1;
		//更新访问序列
		m_map[key] = update(it->second);
		return m_map[key]->val;
	}

	void set(int key, int value) {
		Map::iterator it = m_map.find(key);
		if (it != m_map.end())
		{
			m_map[key] = update(it->second);
			m_map[key]->val = value;
		}
		else
		{
			if (m_list.size() < m_capacity)
			{
				m_map[key] = m_list.insert(m_list.end(), node(key, value));
			}
			else
			{
				m_map.erase(m_list.front().key);
				//删除最久未使用的节点,插入新节点
				m_list.pop_front();
				m_map[key] = m_list.insert(m_list.end(), node(key, value));
			}
		}
	}
};



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值