题目描述
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路(哈希表 + 双向链表)
用哈希表存储键值(key)与其对应结点,使得get达到O(1)的时间复杂度。
双向链表模拟缓存机制。初始化一个头结点和一个尾结点,当新插入结点或刚刚访问过结点(get)时,将该结点插到头结点后,如果此时双向链表中(除了头尾结点)的结点数超过了缓存容量,则删除尾结点前一个结点,即最近都未访问过的结点。插入和删除操作同时还要更新哈希表。访问结点后要更新结点对应的value。
代码(c++)
class LRUCache {
private:
struct LinkNode{
int key;
int value;
LinkNode* left;
LinkNode* right;
LinkNode(int x,int y): key(x),value(y),left(NULL),right(NULL){}
};
map<int,LinkNode*> hashTable;
LinkNode* head;
LinkNode* tail;
int size=0;
int capacity;
public:
LRUCache(int capacity) {
this->capacity=capacity;
head=new LinkNode(-1,-1);
tail=new LinkNode(-1,-1);
head->right=tail;
tail->left=head;
}
int get(int key) {
if(hashTable.find(key)==hashTable.end()) return -1;
updateNode(hashTable[key]);
return hashTable[key]->value;
}
void put(int key, int value) {
if(hashTable.find(key)==hashTable.end()){
LinkNode* new_node=new LinkNode(key,value);
add(new_node);
hashTable[key]=new_node;
size+=1;
if(size>capacity){
remove();
size-=1;
}
}
else{
hashTable[key]->value=value;
updateNode(hashTable[key]);
}
}
void updateNode(LinkNode* node){
LinkNode* pre=node->left;
LinkNode* post=node->right;
pre->right=post;
post->left=pre;
add(node);
}
void add(LinkNode* &node){
head->right->left=node;
node->right=head->right;
head->right=node;
node->left=head;
}
void remove(){
LinkNode* pre=tail->left->left;
LinkNode* d=tail->left;
int key=d->key;
pre->right=tail;
tail->left=pre;
d->left=NULL;
d->right=NULL;
delete(d);
hashTable.erase(hashTable.find(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);
*/