admin 管理员组

文章数量: 887021

LRU##

NC93设计LRU缓存结构 =190&&tqId=35214&rp=1&ru=/ta/job-code-high-rd&qru=/ta/job-code-high-rd/question-ranking
class Solution {
public:vector<int> LRU(vector<vector<int> >& operators, int k) {vector<int>v;for(auto opt:operators){if(opt[0]==1){set(opt[1],opt[2],k);}else if(opt[0]==2){int value=get(opt[1]);v.push_back(value);}}return v;}
private:unordered_map<int,int>map;list<int>list;void set(int key,int value,int k){if(list.size()==k){int delkey=list.back();list.pop_back();map.erase(delkey);}list.push_front(key);map[key]=value;}int get(int key){auto it=map.find(key);if(it!=map.end()){list.remove(it->first);list.push_front(it->first);return it->second;}else{return -1;}}
};// class LRUcache{
// public:
//     LRUcache(int capacity):k(capacity){}
//     void put(int key,int value){
//         if(list.size()==k){
//             int delkey=list.back();
//             list.pop_back();
//             map.erase(delkey);
//         }
//         list.push_front(key);
//         map[key]=value;
//     }
//     int get(int key){
//         auto it=map.find(key);
//         if(it!=map.end()){
//             list.remove(it->first);
//             list.push_front(it->first);
//             return it->second;
//         }else{
//             return -1;
//         }
//     }
// private:
//     unordered_map<int,int>map;
//     list<int>list;
//     int k;
// };

本文标签: LRU