LeetCode_146. LRU Cache

題目描述:
在這裏插入圖片描述
思路:解題思路

class LRUCache {
public:
    LRUCache(int capacity) {
        n=capacity;
    }
    
    int get(int key) {
        auto it=m.find(key);
        if(it!=m.end()){
            int ans=it->second->second;
            lis.erase(it->second);
            lis.push_front(make_pair(key,ans));
            it->second=lis.begin();
                return ans;
        }else
            return -1;
    }
    
    void put(int key, int value) {
        auto it=m.find(key);
        if(it!=m.end()){
            lis.erase(it->second);
            lis.push_front(make_pair(key,value));
            m[key]=lis.begin();
        }else if(m.size()<n){
            lis.push_front(make_pair(key,value));
            m[key]=lis.begin();
        }else{
            auto it=lis.end();
            it--;
            m.erase(it->first);//map是按照可以刪除
            lis.erase(it);//list按照指針刪除
            lis.push_front(make_pair(key,value));
            m[key]=lis.begin();
        }
    }
private:
    list<pair<int,int>> lis;//雙向循環鏈表
    map<int,list<pair<int,int>>::iterator> m;//(key,value)->(key,iterator)
    int n;
};

/**
 * 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);
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章