zoukankan      html  css  js  c++  java
  • leetcode:146. LRU缓存机制

    题目描述:

    运用你所掌握的数据结构,设计和实现一个  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

    思路分析:

    这个最近最少使用的缓存机制,之前在学习操作系统时了解过。需要在O(n)时间复杂度能完成写入数据和获取数据。考虑用hash,由于要维护的缓存是需要对于最新输入的结点将其移动到开头,数组做移动操作需要O(n),所以用链表来存储这个缓存,可以保证插入和删除操作的O(1)时间内。再利用一个map来存储出现过的结点,可以在O(1)时间内找到出现过的结点并更新。但这里需要在找到这个结点的同时,找到其在缓存中的位置,方便做插入删除,因此这个map<int, list>, 即将这个结点的对应指针作为值保存。这里注意用到的map中的list是一个iterator,方便直接调用begin和end函数。

    代码:

     1 class LRUCache {
     2 public:
     3     LRUCache(int capacity): capacity(capacity) {}
     4     
     5     int get(int key) {
     6         if(pos.find(key) != pos.end())
     7         {
     8             put(key, pos[key]->second);
     9             return pos[key]->second;
    10         }
    11         return -1;
    12     }
    13     
    14     void put(int key, int value) {
    15         if(pos.find(key) != pos.end())
    16         {
    17             recent.erase(pos[key]);
    18         }
    19         else
    20         {
    21             if(recent.size() >= capacity)
    22             {
    23                 pos.erase(recent.back().first);
    24                 recent.pop_back();
    25             }
    26         }
    27         recent.push_front({key, value});
    28         pos[key] = recent.begin();
    29     }
    30 private:
    31     int capacity;
    32     list<pair<int, int>> recent;
    33     unordered_map<int, list<pair<int, int>>::iterator> pos;
    34 };
    35 
    36 /**
    37  * Your LRUCache object will be instantiated and called as such:
    38  * LRUCache* obj = new LRUCache(capacity);
    39  * int param_1 = obj->get(key);
    40  * obj->put(key,value);
    41  */
  • 相关阅读:
    HDU 5528 Count a * b 欧拉函数
    HDU 5534 Partial Tree 完全背包
    HDU 5536 Chip Factory Trie
    HDU 5510 Bazinga KMP
    HDU 4821 String 字符串哈希
    HDU 4814 Golden Radio Base 模拟
    LA 6538 Dinner Coming Soon DP
    HDU 4781 Assignment For Princess 构造
    LA 7056 Colorful Toy Polya定理
    LA 6540 Fibonacci Tree
  • 原文地址:https://www.cnblogs.com/LJ-LJ/p/11204068.html
Copyright © 2011-2022 走看看