LRU(leastLeast Recently Used)

Posted 黑桃_K_

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LRU(leastLeast Recently Used)相关的知识,希望对你有一定的参考价值。

一、什么是LRU

最近最少使用的内存管理算法

长期不被使用的数据,在未来被使用的概率也不大,所以当内存达到一定的交换阈值,会将最近最少使用的数据移除。

二、使用方法

采用哈希表双向链表结合方式,使得访问数据。插入数据的效率达到O(1)。

哈希表: unordered_map<int,list<int,pair<int,int>::iterator>
链表: list<pair<int,int>>

采用哈希表可以使得查找效率达到O(1) ,哈希表的第二个值存储链表的迭代器

三、代码(内有注释)

class LRUCache 
public:
    LRUCache(int capacity) 
    //确定链表的节点数
        _capacity=capacity;
    
  //查找节点值,直接从哈希表中查找,找不到返回-1
  //找到的话,找到节点值,然后将这个节点前后的节点相连,将此节点移动的链表的最后位置
  //此处采用list自带的splice 函数 (哪个位置,链表,移动链表的那个节点);  
    int get(int key) 
        auto umit=_hashMap.find(key);
        if(umit!=_hashMap.end())
            LRU_LST_IT listIt=umit->second;
            int value=listIt->second;
            _listCache.splice(_listCache.end(),_listCache,listIt);
            //连接左右,取出值放在后面
            //_listCache.erase(listIt);
            //_hashMap.erase(key);
            //_listCache.push_back(make_pair(key,value));
            //_hashMap[key]=--_listCache.end();
            return value; 
        else
            return -1;
        

    
 
 //插入节点
 //当前哈希表中是否存在
 //存在则直接将当前节点移动到链表最后
 //不存在则判断链表个节点个数是否满了
 //满了,则删除掉最前面的节点和哈希表中的最前面节点信息
 //然后将新节点插入到链表后面,并且构建哈希表的key-value信息
 //
 //不满则直接在链表后面插入新节点,并且构建哈希表的key-value信息   
    void put(int key, int value) 
        auto umit=_hashMap.find(key);
        if(umit!=_hashMap.end())
            //auto endit=_listCache.end();
            LRU_LST_IT ltIt=umit->second;
            ltIt->second=value;
            _listCache.splice(_listCache.end(),_listCache,umit->second);
            
        else
            if(_listCache.size()==_capacity)
                _hashMap.erase(_listCache.front().first);
                _listCache.pop_front();
            

            _listCache.push_back(make_pair(key,value));

            _hashMap[key]=--_listCache.end();    
        
    
private:
    typedef list<std::pair<int,int>>::iterator  LRU_LST_IT;
    typedef std::pair<int,int> LRU_LST; 
//链表定义 哈希表定义 节点个数
    list<LRU_LST> _listCache;
    unordered_map<int,LRU_LST_IT> _hashMap; 
    int _capacity;
;


四、图

以上是关于LRU(leastLeast Recently Used)的主要内容,如果未能解决你的问题,请参考以下文章

LRU(leastLeast Recently Used)

Redis精通系列——LRU算法详述(Least Recently Used - 最近最少使用)

LRU(Least Recently Used最近最少使用)的c++实现(顺序表)

LRU算法

关于LRU算法(转载)

LRU Cache