***Leetcode 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.

沒做出來。。。

class LRUCache {
public:

    // KEY
    using LIS = list<int>;
    // TUPLE
    using TUPLE = tuple <int, LIS::iterator>;
    // KEY, TUPLE
    using MAP = unordered_map<int, TUPLE>;
    
    LRUCache(int capacity) {
        size = capacity;
    }
    
    int get(int key) {
        auto it = mp.find(key);
        if (it == end(mp)) {
            return -1;
        }
 
        ls.erase(std::get<1>(it->second));
        ls.push_front(key);
        std::get<1>(it->second) = begin(ls);
        
        return std::get<0>(it->second); 
    }
    
    void put(int key, int value) {
        
        auto it = mp.find(key);
        if (it != end(mp)) {
            if (value != std::get<0>(it->second)) {
                ls.erase(std::get<1>(it->second));
                ls.push_front(key);
                std::get<1>(it->second) = begin(ls);
                std::get<0>(it->second) = value;
            }
            return;
        }
        
        if (mp.size() == size) {
            mp.erase(ls.back());
            ls.pop_back();
        } 
        ls.push_front(key);
        mp[key] = make_tuple(value,begin(ls));
    }
    
private:

    LIS ls;
    
    size_t size;
    
    // map<key, tuple>
    MAP mp;
    
};

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

發佈了227 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章