• leetcode LRU缓存机制(list+unordered_map)详细解析


    运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

    获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
    写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

    进阶:

    你是否可以在 O(1) 时间复杂度内完成这两种操作?

    示例:

    LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

    cache.put(1, 1);
    cache.put(2, 2);
    cache.get(1); // 返回 1
    cache.put(3, 3); // 该操作会使得密钥 2 作废
    cache.get(2); // 返回 -1 (未找到)
    cache.put(4, 4); // 该操作会使得密钥 1 作废
    cache.get(1); // 返回 -1 (未找到)
    cache.get(3); // 返回 3
    cache.get(4); // 返回 4

    题解:

    就是一种缓存淘汰策略。

    计算机的缓存容量有限,如果缓存满了就要删除一些内容,给新内容腾位置。但问题是,删除哪些内容呢?我们肯定希望删掉哪些没什么用的缓存,而把有用的数据继续留在缓存里,方便之后继续使用。那么,什么样的数据,我们判定为「有用的」的数据呢?

    LRU 缓存淘汰算法就是一种常用策略。LRU 的全称是 Least Recently Used,也就是说我们认为最近使用过的数据应该是是「有用的」,很久都没用过的数据应该是无用的,内存满了就优先删那些很久没用过的数据。

    要让 put 和 get 方法的时间复杂度为 O(1)O(1),我们可以总结出 cache 这个数据结构必要的条件:查找快,插入快,删除快,有顺序之分。

    因为显然 cache 必须有顺序之分,以区分最近使用的和久未使用的数据;而且我们要在 cache 中查找键是否已存在;如果容量满了要删除最后一个数据;每次访问还要把数据插入到队头。

    那么,什么数据结构同时符合上述条件呢?哈希表查找快,但是数据无固定顺序;链表有顺序之分,插入删除快,但是查找慢。所以结合一下,形成一种新的数据结构:哈希链表。

    参考代码:

     1 class LRUCache {
     2 private:
     3     list<pair<int,int>> cache;
     4     unordered_map<int, list<pair<int,int>>::iterator> ump;
     5     int cap;
     6 public:
     7     LRUCache(int capacity) {
     8         this->cap=capacity;
     9     }
    10     
    11     int get(int key) {
    12         auto it=ump.find(key);
    13         if(it==ump.end()) return -1;
    14         pair<int,int> pv=*ump[key];
    15         cache.erase(ump[key]);
    16         cache.push_front(pv);
    17         ump[key]=cache.begin();
    18 
    19         return pv.second;
    20     }
    21     
    22     void put(int key, int value) {
    23         auto it=ump.find(key);
    24         if(it==ump.end())
    25         {
    26             if(cache.size()==cap)
    27             {
    28                 ump.erase(cache.back().first);
    29                 cache.pop_back();
    30             }
    31             cache.push_front(make_pair(key,value));
    32             ump[key]=cache.begin();
    33         }
    34         else
    35         {
    36             cache.erase(ump[key]);
    37             cache.push_front(make_pair(key,value));
    38             ump[key]=cache.begin();
    39         }
    40     }
    41 };
    42 
    43 /**
    44  * Your LRUCache object will be instantiated and called as such:
    45  * LRUCache* obj = new LRUCache(capacity);
    46  * int param_1 = obj->get(key);
    47  * obj->put(key,value);
    48  */
    C++
  • 相关阅读:
    Spring第一次测试错题解析
    正则回顾
    Spring经典---AOP
    动态代理
    MyBatis第一次测试卷---错题分析
    JS中对数组元素进行增删改移
    限制条件补全代码系列题
    字符串去空格
    数组去重
    数组排序
  • 原文地址:https://www.cnblogs.com/csushl/p/12374740.html
Copyright © 2020-2023  润新知