每日一题 146. LRU缓存机制

146. LRU缓存机制

源代码(记录一下):
class LRUCache {
private:
    list<pair<int, int>> cache;
    unordered_map<int, list<pair<int, int>>::iterator> cache_hash;
    int max_capacity = 0;
    int c_capacity = 0;
public:
    LRUCache(int capacity) {
        this->max_capacity = capacity;
    }
    
    int get(int key) {
        if(cache_hash.find(key) == cache_hash.end()) return -1;
        else{
            // 每一次都把找到的元素移动到cache的首部,这样方便移除
            auto elem = cache_hash.find(key);
            int value = elem->second->second;
            cache.erase(elem->second);
            cache.push_front(make_pair(key, value));
            cache_hash[key] = cache.begin();
            return value;
        }
    }
    
    void put(int key, int value) {
        // 这里写复杂了,,,应该把key存在的情况抽象出来,要不然冗余的代码有些多。。
        if(c_capacity < max_capacity){
            if(cache_hash.find(key) == cache_hash.end()){
                pair<int, int> lis = make_pair(key, value);
                cache.push_front(lis);
                cache_hash.insert({key, cache.begin()});
                c_capacity ++;
            }else{
                auto elem = cache_hash.find(key);
                cache.erase(elem->second);
                cache.push_front(make_pair(key, value));
                cache_hash[key] = cache.begin();
            }
        }else{
            if(cache_hash.find(key) != cache_hash.end()){
                auto elem = cache_hash.find(key);
                cache.erase(elem->second);
                cache.push_front(make_pair(key, value));
                cache_hash[key] = cache.begin();
            }else{
                cache.push_front(make_pair(key, value));
                cache_hash[key] = cache.begin();
                int key = cache.back().first;
                cache_hash.erase(key);
                cache.pop_back();
            }
        }
    }
};

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

你可能感兴趣的:(leetcode随笔,leetcode,算法)