题目
leetcode 146 题
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
来源:力扣(LeetCode)
示例:
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)
分析
- cache中的元素必须有时序,当容量满了后,要删除最久没有被使用的元素
- 在cache中快速找到某个key是否存在,和对于的value
- 每次访问某个key时,都要将这个元素变为最近使用的,所以cache应该支持随机插入和删除操作
- 通过以上分析: 应该使用哈希链表,底层存放[key,val]使用双链表,但是key<—> node 使用map来映射,达到O(1)的时间复杂度
算法
class LRUCache {
private:
struct DoubleListNode{
int key,val;
DoubleListNode* next = nullptr;
DoubleListNode* prev = nullptr;
DoubleListNode(int k = 0,int v = 0):key(k),val(v){
}
};
class DoubleList{
private:
DoubleListNode* head = nullptr;
DoubleListNode* tail = nullptr;
public:
DoubleList(){
head = new DoubleListNode;
tail = new DoubleListNode;
head->next = tail;
tail->prev = head;
}
// 越靠近head,节点未被使用的时间越久
int RemoveFront(){
DoubleListNode* node = head->next;
head->next = node->next;
node->next->prev = head;
return node->key;
}
//添加节点到tail
DoubleListNode* AddBack(int k,int v){
DoubleListNode* node = new DoubleListNode(k,v);
tail->prev->next = node;
node->prev = tail->prev;
node->next = tail;
tail->prev = node;
return node;
}
//把其他的节点变为最近使用
void MoveLast(DoubleListNode* node){
if(node->next == tail) return ;
node->prev->next = node->next;
node->next->prev = node->prev;
tail->prev->next = node;
node->prev = tail->prev;
node->next = tail;
tail->prev = node;
}
void MoveLast(DoubleListNode* node,int v){
node->val = v;
MoveLast(node);
}
~DoubleList(){
while(head){
DoubleListNode* node = head->next;
delete head;
head = node;
}
}
};
private:
int capacity_ = 0;
int size_ = 0;
DoubleList list_;
unordered_map<int ,DoubleListNode*> hash_list_;
public:
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
// 如果不存在,返回-1
if(hash_list_.count(key) == 0) return -1;
list_.MoveLast(hash_list_[key]);
return hash_list_[key]->val;
}
void put(int key, int value) {
if(hash_list_.count(key) != 0){
list_.MoveLast(hash_list_[key],value);
return;
}
if(size_ >= capacity_){
hash_list_.erase(list_.RemoveFront());
size_--;
}
hash_list_[key] = list_.AddBack(key,value);
size_++;
}
};