leetcode LRU Cache

本文介绍了如何利用STL中的双向链表List和哈希表unordered_map来实现LRU(Least Recently Used)缓存算法。详细解释了结构LRUNode的定义和LRUCache类的get和set方法实现。

本文参考http://www.cnblogs.com/TenosDoIt/p/3417157.html

为了达到快速有效,本题主要使用了STL中的双向链表List和哈希表undered_map, 其中,对两者需要有较为熟练的应用

代码

</pre><pre class="cpp" name="code">struct LRUNode
{
	int key;
	int value;
	LRUNode(int x, int y):key(x), value(y){}
};

class LRUCache
{
public:
	LRUCache(int capacity)
	{
		size = capacity;	
	}

	int get(int key)
	{
		if(mapLRU.find(key) == mapLRU.end())
			return -1;
		else
		{
			listLRU.splice(listLRU.begin(),listLRU, mapLRU[key]);
			mapLRU[key] = listLRU.begin();
			return mapLRU[key]->value;

		}
	
	}

	void set(int key, int value)
	{
		if(mapLRU.find(key) == mapLRU.end())
		{
			if(listLRU.size() == size)
			{	
				mapLRU.erase(listLRU.back().key);
				listLRU.pop_back();
			}

			listLRU.push_front(LRUNode(key, value));
			mapLRU[key] = listLRU.begin();			    
		}
		else
		{
			mapLRU[key]->value = value;
			listLRU.splice(listLRU.begin(), listLRU, mapLRU[key]);
			mapLRU[key] = listLRU.begin();
		
		}
		
			
	}




private:
	int size;
	list<LRUNode> listLRU;
	unordered_map<int, list<LRUNode>::iterator>mapLRU; 


};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值