Leetcode No.146 ****

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

参考博客:http://www.cnblogs.com/grandyang/p/4587511.html

解答:通过构建一个list表,内容为pair<int,int>,即键-值对,用于存放当前的缓存值。同时构建一个Hash表,
unordered_map<int, list<pair<int,int>>::iterator> m 用于存放key-list内容,目的是用于快速查询键值对。
get函数:查询哈希表中是否有输入的key值,没有则返回 -1 ,否则返回相应的值,并用list.splice更新当前键值对在list最前处。
put函数:如果存在键值对,那么则在list中删除该键值对。将新输入的键值对放在list的最前处,并同时更新Hash表中的键值对。
如果容量已经超过最大值,那么将最不常用的键值对(位于list最后处)弹出。同时删除Hash表中的键值对。

函数说明:
【1】unordered_map<int, list<pair<int,int>>::iterator> m;
   auto it=m.find(key); 相当于 list<pair<int,int>>::iterator it;
【2】it->second 表示取到了pair<int,int>
【3】l.splice(l.begin(),l, it->second); 表示将pair<int,int>放置在list的最前端,其余顺序不变。







class LRUCache {
public:
    LRUCache(int capacity) {
     this->capacity=capacity;   
    }
    
    int get(int key) {
    //    list<pair<int,int>>::iterator it;
    auto it=m.find(key);
    if(it==m.end()) return -1;
    l.splice(l.begin(),l, it->second);
    return it->second->second;
    }
    
    void put(int key, int value) {
    //    list<pair<int,int>>::iterator it;
    auto it = m.find(key);
    if (it != m.end()) l.erase(it->second);
    l.push_front(make_pair(key, value));
    m[key] = l.begin();
    if ((int)m.size() > capacity) {
        int k = l.rbegin()->first;
        l.pop_back();
        m.erase(k);
    }
    }
 private:
     int capacity;
     list<pair<int,int>> l;
     unordered_map<int, list<pair<int,int>>::iterator> m;
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */



原文地址:https://www.cnblogs.com/2Bthebest1/p/10853521.html