T1 LC146 LRU缓存机制
struct doubleLinkedNode {
int key, value;
doubleLinkedNode* prev;
doubleLinkedNode* next;
doubleLinkedNode() :key(0), value(0), prev(nullptr), next(nullptr) {};
doubleLinkedNode(int _key, int _value) :key(_key), value(_value), prev(nullptr), next(nullptr) {};
};
class LRUCache {
private:
unordered_map<int, doubleLinkedNode*> cache;
doubleLinkedNode* head;
doubleLinkedNode* tail;
int size;
int capacity;
public:
LRUCache(int _capacity) :capacity(_capacity), size(0) {
head = new doubleLinkedNode();
tail = new doubleLinkedNode();
head->next = tail;
tail->prev = head;
}
int get(int key) {
if (!cache.count(key)) { return -1; }
doubleLinkedNode* node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
if (!cache.count(key)) {
doubleLinkedNode* node = new doubleLinkedNode(key, value);
cache[key] = node;
addToHead(node);
++size;
if (size > capacity) {
doubleLinkedNode* removed = removeTail();
cache.erase(removed->key);
--size;
}
}
else {
doubleLinkedNode* node = cache[key];
node->value = value;
moveToHead(node);
}
}
void addToHead(doubleLinkedNode* node) {
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
void removeNode(doubleLinkedNode* node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
void moveToHead(doubleLinkedNode* node) {
removeNode(node);
addToHead(node);
}
doubleLinkedNode* removeTail() {
doubleLinkedNode* node = tail->prev;
removeNode(node);
return node;
}
};
今日学习总结
- 认真上课
- 数据挖掘起步
- C++ OJ
- 复习 class 基础
- 区块链视频及笔记 - 11
- 极客时间 - 计算机组成原理
今日英语
- 托福单词打卡
- 托福单词打卡*2
- 阅读1000词书-完成
[ ] 单号:T 完成半套 TPO
[ ] 阅读至少一篇
- 听力至少3篇
- 口语全套
- 写作一个
[ ] 双号:GRE 学习三小时
[ ] GRE 核心词汇助记 List*2
- GRE 简单填空*1
- GRE 阅读白皮书 Passage*2