LeetCode Hot100 146.LRU缓存

class LRUCache {
public:
    int capacity;
    int size;
    unordered_map<int, pair<int, list<int>::iterator>> hash;
    list<int> q;   //back as bottom, front as top
    LRUCache(int capacity) {
        this->capacity = capacity;
    }
    int get(int key) {
        if(hash.find(key) == hash.end()) return -1;
        else{// 将访问的键移到链表的前面(最近使用)
            auto value = hash[key].first;
            q.erase(hash[key].second);  
            q.push_front(key);
            hash[key] = pair(value, q.begin());
            return value;
        }
    }
    
    void put(int key, int value) {
        //key不存在
        if(hash.find(key) == hash.end()){
            if(q.size() == this->capacity){
                //delete最久未使用的关键字
                auto ite = hash.find(q.back());
                q.pop_back();
                hash.erase(ite);                
                //insert new key
                q.push_front(key);
                hash[key] = pair(value, q.begin());
            }else if(q.size() < this->capacity){
                q.push_front(key);
                hash[key] = pair(value, q.begin());
            }
        }else{
            //key已存在
            q.erase(hash[key].second);
            q.push_front(key);
            hash[key] = pair(value, q.begin());
        }
    }
};

你可能感兴趣的:(LeetCode每日刷题记录,#,LeetCode中等题,leetcode,哈希算法)