数据结构:
双向链表list:保存key和value
哈希表unordered_map:用于快速找到key对应节点位置
int:记录容器大小,容器满时淘汰数据
使用的函数:
list:
begin()取链表第一个元素;
back()取链表最后一个元素;
size()计算链表一共多少元素;
erase(iterator)删除链表中某个元素;
push_front(pair<>)将某个元素放到链表头部;
pop_back()删除链表最后一个元素。
unordered_map:
count(key)查找key对应元素,存在返回值>0;
erase(key)删除map中key对应的值。
class Solution {
public:
list<pair<int, int>> cache;//创建双向链表
unordered_map<int, list<pair<int, int>>::iterator> map;//创建哈希表
int cap;
Solution(int capacity){
// write code here
cap = capacity;
}
int get(int key) {
// write code here
if (map.count(key) > 0){
auto temp = *map[key];
cache.erase(map[key]);
map.erase(key);
cache.push_front(temp);
map[key] = cache.begin();//映射头部
return temp.second;
}
return -1;
}
void set(int key, int value){
// write code here
if (map.count(key) > 0){
cache.erase(map[key]);
map.erase(key);
}
else if (cap == cache.size()){
auto temp = cache.back();
map.erase(temp.first);
cache.pop_back();
}
cache.push_front(pair<int, int>(key, value));
map[key] = cache.begin();//映射头部
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* solution = new Solution(capacity);
* int output = solution->get(key);
* solution->set(key,value);
*/