146. LRU Cache
题目大意: 设计并实现一个 LRU Cache.
实现对应的函数 get(key), put(key, value).
Follow up: 所有操作 O(1) 时间复杂度.
实现 LRU Cache 的关键数据结构: 双向链表 + 哈希表.
以下实现中, 定义了双向链表结点类 Node. 以及 unordered_map<int, *Node> 类型的 map 变量.
Code 部分
Node 结点类设计:
class Node {
public:
int key;
int value;
Node *pre;
Node *next;
Node(int key, int value) {
this->key = key;
this->value = value;
this->pre = NULL;
this->next = NULL;
}
};
LRUCache 类设计:
LRUCache 中, 包括一个头节点 head, 和一个尾结点 tail. 均不存放数据.
一个 unordered_map 类型的变量 map 用于匹配和存储要查找的 key/<key,value>.
class LRUCache {
private:
int capacity;
int count;
unordered_map<int, Node*> map