146. LRU Cache 最近最少使用置换缓存器

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up:

Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

Difficulty: Hard

这里让设计一个LRU缓存器,LRU(Least Recently Used)就是最少使用的意思.缓存器主要有两个成员函数,get和put.get函数时通过key来获得value,如果成功获得后,这对(key,value)升至缓存器中最常用的位置(顶部),如果key不存在,则返回-1. put函数时插入一堆新的(key,value)如果原缓存器中有该key,则需要先删除原来的,也就是底部的值. 具体实现需要三个私有变量,cap,l和m.cap是缓存器的容量大小,l是保存缓存器内容的列表.m是保存key和缓存器列表l的迭代器之间的映射的哈希表.

class LRUCache {
public:
    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
        auto it = m.find(key);
        if (it == m.end()) return -1;
        /*
        splice
        例:l1.splice(l1.begin(), l2, it)
         list(链表)合并,从l2出取it(迭代器)放到l1的begin.l2里面it出没有了,it也失效
        */
        //it是迭代器,it->second是迭代器对应索引上的值,这里是pair
        l.splice(l.begin(),l,it->second);
        return it->second->second;
    }
    
    void put(int key, int value) {
        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 (m.size()>cap){
            int k = l.rbegin()->first;
            l.pop_back();
            m.erase(k);
        }
    }
private: 
    int cap;
    list<pair<int,int>> l; //list是链表,vector是数组,l保存缓存器内存的列表
    unordered_map<int,list<pair<int,int>>::iterator> m; //保存key和缓存器l中迭代器的映射
};

/**
 * 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);
 */
 
comments powered by Disqus