十七
十七
Published on 2024-09-27 / 44 Visits
0
0

leetcode146. LRU 缓存

题目

题解

class LRUCache {
private:
    int capacity;
    list<pair<int,int>>cache;
    unordered_map<int,list<pair<int,int>>::iterator> mp;
public:
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    
    int get(int key) {
        if(mp.find(key) == mp.end())return -1;
        else{
            auto it_key = *mp[key]; 
            cache.erase(mp[key]);
            cache.push_front(it_key);
            mp[key] = cache.begin();
            return it_key.second;
        }
    }
    void put(int key, int value) {
        if(mp.find(key)==mp.end()){
            if(cache.size()==capacity){
                mp.erase(cache.back().first);
                cache.pop_back();
            }
        }else{
                cache.erase(mp[key]);
            }
        cache.push_front({key,value});
        mp[key]=cache.begin();
    }


};

/**
 * 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);
 */


Comment