面试高频题
//定义一个双向链表(不是循环链表)
struct node{
int key;
int val;
node *next;
node *pre;
node(int x,int y):key(x),val(y),next(nullptr),pre(nullptr){}
};
class LRUCache {
public:
//定义一个哈希表,哈希表只负责通过key来查找节点
unordered_map<int, node*> umap;
int size;
node *head;
node *tail;
LRUCache(int capacity) {
size = capacity;//这个size在删除加入的时候不需要更新,因为这个是容量
head = nullptr;
tail = nullptr;
}
// 获取缓冲区中 key 对应的 value
// 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
int get(int key) {
if(umap.count(key)){
node *cur = umap[key];
int val = cur->val;
//先将节点删除在双向链表中删除,将该节点加入到头部
remove(cur);
sethead(cur);
return val;
}else return -1;
}
// 将key-value值存入缓冲区
void put(int key, int value) {
if(umap.count(key)){
node *cur = umap[key];
cur->val = value;
//先将节点删除在双向链表中删除,将该节点加入到头部
//unordered_map<int ,node*> :: iterator pos =umap.find(key);
remove(cur);
sethead(cur);
}else{
node *tem = new node(key,value);
if(umap.size() >= size){
unordered_map<int,node*>:: iterator pos = umap.find(tail->key);
remove(tail);
umap.erase(pos);
}
sethead(tem);
umap[key] = tem;
}
}
void remove(node *cur){
if(cur == head && cur == tail){
head =nullptr;
tail = nullptr;
return;
}
if(cur == head) head = cur->next;
else if(cur == tail) tail = cur->pre;
else{
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
}
}
void sethead(node *cur){
cur->next = head;
if(head != nullptr) head->pre = cur;
head = cur;
if (tail == nullptr){//如果链表为空,加入链表时,头和尾都需要更新
tail = cur;
}
}
};