LRU缓存机制(哈希链表)

题目:https://leetcode-cn.com/problems/lru-cache/
参考:https://leetcode-cn.com/problems/lru-cache/solution/lru-ce-lue-xiang-jie-he-shi-xian-by-labuladong/
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

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

class LRUCache {
public:
    int cap;
    list<pair<int,int> > li;
    unordered_map<int,list<pair<int,int> >::iterator> mp;
    
    LRUCache(int capacity) {
        cap = capacity;
        li.clear();
        mp.clear();
    }
    
    int get(int key) {
        auto it = mp.find(key);
        if(it == mp.end()) return -1;
        pair<int,int> p = *mp[key];
        li.erase(mp[key]);//删除数据
        li.push_front(p);//更新链表
        mp[key] = li.begin();//更新map
        return p.second;
    }
    
    void put(int key, int value) {
        auto it = mp.find(key);
        if(it == mp.end()) {//原key不存在
            if(li.size() == cap) {//满容器删back()
                mp.erase(mp.find(li.back().first));
                li.pop_back();
            }
            //加入数据,更新list/map
            li.push_front(make_pair(key,value));
            mp[key] = li.begin();
        }else {//key存在
            pair<int,int> p = *mp[key];
            p.second = value;
            li.erase(mp[key]);//删除数据
            li.push_front(p);//更新链表
            mp[key] = li.begin();//更新map
        }
    }
};


/**
 * 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);
 */
发布了152 篇原创文章 · 获赞 2 · 访问量 6457

猜你喜欢

转载自blog.csdn.net/weixin_43918473/article/details/104634642