C++实现LRU

什么是LRU Cache

LRU是Least Recently Used的缩写,意思是最近最少使用,它是一种Cache替换算法。 什么是Cache?狭义的Cache指的是位于CPU和主存间的快速RAM, 通常它不像系统主存那样使用DRAM技术,而使用昂贵但较快速的SRAM技术。 广义上的Cache指的是位于速度相差较大的两种硬件之间, 用于协调两者数据传输速度差异的结构。除了CPU与主存之间有Cache, 内存与硬盘
之间也有Cache,乃至在硬盘与网络之间也有某种意义上的Cache── 称为Internet临时文件夹或网络内容缓存等。

在这里插入图片描述

Cache的容量有限,因此当Cache的容量用完后,而又有新的内容需要添加进来时, 就需要挑选并舍弃原有的部分内容,从而腾出空间来放新内容。LRU Cache 的替换原则就是将最近最少使用的内容替换掉。 其实,LRU译成最久未使用会更形象, 因为该算法每次替换掉的就是一段时间内最久没有使用过的内容。

LRU Cache的实现

实现LRU Cache的方法和思路很多,但是要保持高效实现O(1)的put和get,那么使用双向链表和哈希表的搭配是最高效和经典的。使用双向链表是因为双向链表可以实现任意位置O(1)的插入和删除,使用哈希表是因为哈希表的增删查改也是O(1)。
在这里插入图片描述

LRU Cache的OJ

https://leetcode-cn.com/problems/lru-cache/

class LRUCache{
public:
	LRUCache(int capacity)
		:_capacity(capacity)
	{}
	
	int get(int key)
	{
		auto ret = _hashmap.find(key);
		if(ret != _hashmap.end())
		{
			//更新key对应的位置
			LtIter it = ret->second;
			//1.erase+push_front 更新迭代器,原迭代器失效
			//2.splice转移节点
			_LRUlist.splice(_LRUlist.begin(), _LRUlist, it);
			
			return it->second;
		}
		else
		{
			return -1;
		}
	}
	
	void put(int key, int value)
	{
		//1.新增
		//2.更新 
		auto ret = _hashmap.find(key);
		if(it == _hashmap.end())
		{
			//满了,先删除LRU的数据
			if(_capacity == _hashmap.size())
			{
				pair<int, int> back = _LRUlist.back();
				_hashmap.erase(back.first);
				_LRUlist.pop_back();
			}
			
			_LRUlist.push_front(make_pair(key, value));
			_hashmap[key] = _LRUlist.begin();
		}
		else
		{
			//更新key对应的位置
			LtIter it = ret->second;
			it->second = value;
			
			_LRUlist.splice(_LRUlist.begin(), _LRUlist, it);
		}
	}
		
private:
	typedef list<pair<int, int>>::iterator LtIter;

	list<pair<int, int>> _LRUlist;            // 将最近用过的往链表的投上移动,保持LRU
	size_t _capacity;                      // 容量大小,超过容量则换出,保持LRU
	unordered_map<int, list<pair<int, int>>::iterator> _hashmap;
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值