link
class LRUCache {
public:
int cap;
int size;
unordered_map<int,int> ktov; // key to value
unordered_map<int,list<int>::iterator> ktoi; // key to iterator
list<int> li;
LRUCache(int capacity) {
cap=capacity;
size=0;
}
int get(int key) {
if(ktov.find(key)==ktov.end()) return -1;
li.erase(ktoi[key]);
li.push_back(key);
ktoi[key]=--li.end();
return ktov[key];
}
void put(int key, int value) {
if(ktov.find(key)!=ktov.end()){
ktov[key]=value;
li.erase(ktoi[key]);
li.push_back(key);
ktoi[key]=--li.end();
}else{
if(size>=cap){
--size;
int del=li.front();
li.pop_front();
ktov.erase(del);
ktoi.erase(del);
}
li.push_back(key);
ktov[key]=value;
ktoi[key]=--li.end();
++size;
}
}
};
/**
* 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);
*/