IT评测·应用市场-qidao123.com
标题:
Grind 75 - Leetcode146 LRU缓存
[打印本页]
作者:
傲渊山岳
时间:
2024-7-11 08:10
标题:
Grind 75 - Leetcode146 LRU缓存
Leetcode146 LRU缓存
经典题,典型compund data structure思想
link
思绪
:
主要思想就是hash table + double-linked list
重点就是手动实现这些功能
因为get和put都要求 O ( 1 ) O(1) O(1)时间内实现,所以就是要用hash table
而要实现LRU,所以用双向链表维护近来使用
ps: code 多打几遍就认识了
class Node {
public:
int key;
int value;
Node *last, *next;
Node(int k = 0, int val = 0) : key(k), value(val), last(nullptr), next(nullptr) {}
};
class LRUCache {
private:
unordered_map<int, Node*> cache;
int size;
int capacity;
Node *head;
Node *tail;
void addNode(Node *node) {
node->next = head->next;
head->next->last = node;
node->last = head;
head->next = node;
}
void deleteNode(Node *node) {
node->last->next = node->next;
node->next->last = node->last;
}
void move(Node *node) {
deleteNode(node);
addNode(node);
}
Node *deleteTail() {
Node *node = tail->last;
deleteNode(node);
return node;
}
public:
LRUCache(int capacity) : capacity(capacity), size(0) {
head = new Node();
tail = new Node();
head->next = tail;
tail->last = head;
}
int get(int key) {
if (cache.count(key) == 0)
return -1;
Node *node = cache[key];
move(node);
return node->value;
}
void put(int key, int value) {
if (cache.count(key) > 0) {
Node *node = cache[key];
node->value = value;
move(node);
}
else {
Node *node = new Node(key, value);
cache[key] = node;
addNode(node);
++size;
if (size > capacity) {
Node *lastUsed = deleteTail();
cache.erase(lastUsed->key);
--size;
delete lastUsed;
}
}
}
};
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/)
Powered by Discuz! X3.4