使用了一個hash表和一個鏈表,每次訪問元素(get)或是添加元素都將元素置於鏈表的頭部,尾部的自然就是最久未使用的。
hash表存儲元素在鏈表中的位置,鏈表儲存key-value,以方便超出容量時從hash表移除舊元素。
class LRUCache {
public:
unordered_map<int, list<pair<int, int>>::iterator> ump;
list<pair<int, int>> values;
int size;
LRUCache(int capacity) {
size = capacity;
}
int get(int key) {
if (ump.count(key)) {
auto now = *ump[key];
int value = now.second;
values.erase(ump[key]);
values.push_front(now);
ump[key] = values.begin();
return value;
}
return -1;
}
void put(int key, int value) {
if (ump.count(key)) {
values.erase(ump[key]);
}
values.push_front(make_pair(key, value));
ump[key] = values.begin();
if (values.size() > size) {
pair<int, int> end = (pair<int, int> &&) values.back();
ump.erase(end.first);
values.pop_back();
}
}
};
/**
* 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);
*/