0
点赞
收藏
分享

微信扫一扫

蓝桥杯 题库 简单 每日十题 day11

安七月读书 2023-09-28 阅读 35

原题链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

感谢博主题解点拨思路:LeetCode 0146. LRU 缓存:双向链表 + 哈希-CSDN博客

题目描述

样例1:

输入

输出

解释

Tag

题目分析

LRU算法需要维护最久未使用的关键字,题目要求put和get都是O(1)复杂度,所使用的数据结构需要O(1)查询到关键字所在位置,并将位置调整到最近使用,同时给出关键字需要O(1)时间内得到value值。

思路

get中查询value做到O(1)比较容易,可以使用哈希表实现(此题使用map)。

put中在O(1)时间内使新加入元素调整到最近使用很多数据结构都能做到,诸如链表插头(尾)、队列入队、入栈等,调整节点位置包括找到节点位置+移动节点,O(1)调整位置直接用这些数据结构则不行。因此我们采用map<int,node*>的方式存储,根据关键字直接查到链表节点的地址,从而根据地址可以直接对节点进行操作。

设计链表头结点为最近使用,尾节点为最久未使用。节点位置在O(1)时间内找到后,需要将节点从原位置调整至队首,同时超过缓存容量还要删除节点(队尾元素)。使用单链表可以做到移动节点,但无法快速删除尾节点,而使用双向链表删除尾节点后,可以根据指向前一个节点的prev指针将前一个节点设为尾节点,下次溢出时可以快速删除。

C++代码

class node{
public:
node *prev,*next;
int key;
int value;
node(node *prev,node *next,int key,int value)
{
this->key = key;
this->value = value;
this->prev = prev;
this->next = next;
}

};

class LRUCache {
private:
int capacity;
unordered_map<int,node*> mp;//node*:节点指针,存储链表中某个节点地址
node *head,*tail;

public:
LRUCache(int capacity) {
this->capacity = capacity;
head = new node(nullptr,nullptr,0,0);
tail = new node(head,nullptr,0,0);
head->next = tail;
}

void adjust(node* temp) //将node移动到队首
{
temp->next = head->next;
temp->prev = head;
head->next = temp;
temp->next->prev = temp;
}

int get(int key) {
if(mp.count(key)){
node* move = mp[key];
/*删除节点*/
move->prev->next = move->next;
move->next->prev = move->prev;
adjust(move);
return mp[key]->value;
}
return -1;
}

void put(int key, int value) {
if(mp.count(key)){
node* temp = mp[key];
mp[key]->value = value;//改值
//删节点
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
adjust(temp);//调位置
}else{
node* newnode = new node(head,head->next,key,value);
head->next->prev = newnode;
head->next = newnode;
mp[key] = newnode;
}
if(mp.size()>capacity){
node* del = tail->prev;
tail->prev = del->prev;
del->prev->next = tail;
mp.erase(del->key);
}
}
};

/**
* 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);
*/

Debug

以下是我自己本地debug时用的代码


int main()
{
freopen("stdin.txt","r",stdin);
string op;
LRUCache* obj = nullptr;
while(cin>>op){
if(op=="cache"){
int capacity;
cin>>capacity;
obj = new LRUCache(capacity);
cout<<"null ";
}else if(op == "get"){
int key;
cin>>key;
cout<<obj->get(key)<<" ";
}else{
int key,value;
cin>>key>>value;
obj->put(key,value);
cout<<"null ";
}
}
}
cache
2
put
1 1
put
2 2
get
1
put
3 3
get
2
put
4 4
get
1
get
3
get
4

举报

相关推荐

0 条评论