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.
#include <list>
class LRUCache{
public:
// @param capacity, an integer
LRUCache(int capacity) {
// write your code here
this->capacity = capacity;
}
// @return an integer
int get(int key) {
// write your code here
if (!hash.count(key)) {
return -1;
}
cache.push_front(Node(key, hash[key]->val));
cache.erase(hash[key]);
hash[key] = cache.begin();
return cache.front().val;
}
// @param key, an integer
// @param value, an integer
// @return nothing
void set(int key, int value) {
// write your code here
if (hash.count(key)) {
cache.erase(hash[key]);
} else {
if (cache.size() == capacity) {
hash.erase(cache.back().key);
cache.pop_back();
}
}
cache.push_front(Node(key, value));
hash[key] = cache.begin();
}
class Node {
public:
int key, val;
Node(int _key, int _val) : key(_key), val(_val){}
};
int capacity;
list<Node> cache;
unordered_map<int, list<Node>::iterator> hash;
};