天天看點

leetcode 146. LRU緩存機制

運用你所掌握的資料結構,設計和實作一個  LRU (最近最少使用) 緩存機制。它應該支援以下操作: 擷取資料 get 和 寫入資料 put 。

擷取資料 get(key) - 如果關鍵字 (key) 存在于緩存中,則擷取關鍵字的值(總是正數),否則傳回 -1。

寫入資料 put(key, value) - 如果關鍵字已經存在,則變更其資料值;如果關鍵字不存在,則插入該組「關鍵字/值」。當緩存容量達到上限時,它應該在寫入新資料之前删除最久未使用的資料值,進而為新的資料值留出空間。

思路:unoedered_map用來查找,list(stl版)用來維護LRU機制 PS:還是STL用的不熟啊!!!

class LRUCache {
public:

    int size = 0;
    unordered_map<int, std::list<std::pair<int, int>>::iterator> st;
    std::list<std::pair<int, int>>lt;
    LRUCache(int capacity) {
        size = capacity;
       
    }
    int get(int key) {
        int ans = -1;
        auto ite = st.find(key);
        if(ite!=st.end()){
             ans = ite->second->second;
             lt.splice(lt.begin(), lt, ite->second);
        }
        return ans;
    }
    void put(int key, int value) {
            auto ite = st.find(key);
            if(ite != st.end()){
                ite->second->second =  value;
                lt.splice(lt.begin(), lt, ite->second);
                return;
            }
            if(st.size() >= size){
                auto i = lt.back();
                lt.pop_back();
                ite = st.find(i.first);
                st.erase(ite);  
            }
            lt.emplace_front(pair<int, int>(key, value));
            st[key] = lt.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);
 */
           

繼續閱讀