Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(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.
Solution:
class LRUCache{
public:
vector<int> keys;
unordered_map<int, int> map;
int size = ;
LRUCache(int capacity) {
size = capacity;
} void adjust(int key){
int idx = -;
for(int i = keys.size() - ; i >= ; i --)
if(keys[i] == key){
idx = i;
break;
} if(idx == -)
return; keys.erase(keys.begin() + idx);
keys.push_back(key);
} int get(int key) {
if(map.find(key) == map.end()){
return -;
}else{
adjust(key);
return map[key];
}
} void set(int key, int value) {
if(map.find(key) != map.end()){
map[key] = value;
adjust(key);
return;
} if(keys.size() >= size ){
int key_to_erase = keys[];
keys.erase(keys.begin());
map.erase(key_to_erase);
} keys.push_back(key);
map[key] = value;
}
};