请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
示例:
输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
提示:
1 <= capacity <= 3000
0 <= key <= 10000
0 <= value <= 105
最多调用 2 * 105 次 get 和 put
- struct DoubleLinkNode{
- int key;
- int value;
- DoubleLinkNode* next;
- DoubleLinkNode* prev;
- DoubleLinkNode():key(0),value(0),next(nullptr),prev(nullptr){}
- DoubleLinkNode(int k,int v):key(k),value(v),next(nullptr),prev(nullptr){}
- };
-
- class LRUCache {
- public:
- LRUCache(int capacity):size(0),capacity(capacity) {
-
- dummy_head=new DoubleLinkNode();
- dummy_tail=new DoubleLinkNode();
- dummy_head->next=dummy_tail;
- dummy_tail->prev=dummy_head;
- }
-
- int get(int key) {
- if(!cache.count(key)){
- return -1;
- }else{
- DoubleLinkNode* node=cache[key];
- moveToHead(node);
- return node->value;
- }
- }
-
- void put(int key, int value) {
-
- if(cache.count(key)){
- DoubleLinkNode* node=cache[key];
- node->value=value;
- moveToHead(node);
- }else{
- DoubleLinkNode* node=new DoubleLinkNode(key,value);
- cache[key]=node;
- addToHead(node);
- size++;
- if(size>capacity){
- DoubleLinkNode* del=deleteTail();
- cache.erase(del->key);
- --size;
- delete del;
- }
- }
- }
-
- void addToHead(DoubleLinkNode* node){
- node->next=dummy_head->next;
- node->prev=dummy_head;
-
- dummy_head->next->prev=node;
- dummy_head->next=node;
- }
-
- void removeNode(DoubleLinkNode* node){
- node->next->prev=node->prev;
- node->prev->next=node->next;
- }
-
- void moveToHead(DoubleLinkNode* node){
- removeNode(node);
- addToHead(node);
- }
-
- DoubleLinkNode* deleteTail(){
- DoubleLinkNode* node=dummy_tail->prev;
- removeNode(node);
- return node;
- }
-
- private:
- unordered_map<int,DoubleLinkNode*>cache;
- int size;
- int capacity;
- DoubleLinkNode* dummy_head;
- DoubleLinkNode* dummy_tail;
- };
-
- /**
- * 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);
- */