146. LRU 缓存
146. LRU 缓存
https://leetcode.cn/problems/lru-cache/description/
思路
https://zhuanlan.zhihu.com/p/85846117
Code
class NODE{ public: NODE* prev; NODE* next; int key; int value; NODE(int key1, int value1){ key = key1; value = value1; } }; class NODEList{ public: NODE* head = NULL; NODE* tail = NULL; NODEList(){ } void push_front(NODE* one){ if (head == NULL){ head = one; one->next = NULL; tail = one; one->prev = NULL; } else { one->next = head; head->prev = one; head = one; head->prev = NULL; } } void push_back(NODE* one){ if (tail == NULL){ tail = one; one->prev = NULL; head = one; one->next = NULL; } else { one->prev = tail; tail->next = one; tail = one; tail->next = NULL; } } void delete_one(NODE* one) { if (head == one && tail == one){ head = NULL; tail = NULL; } else if (head == one) { head = one->next; head->prev = NULL; } else if (tail == one) { tail = one->prev; tail->next = NULL; } else { NODE* prev = one->prev; NODE* next = one->next; prev->next = next; next->prev = prev; } } }; class LRUCache { public: int capacity; int count; map<int, NODE*> query; class NODEList nodelist; LRUCache(int capacity1) { capacity = capacity1; count = 0; } int get(int key) { // cout << "call get with key=" << key << endl; if (!query.contains(key)){ return -1; } NODE* one = query[key]; nodelist.delete_one(one); nodelist.push_back(one); return query[key]->value; } void put(int key, int value) { // cout << "call put key=" << key << ", value=" << value << endl; if (query.contains(key)){ nodelist.delete_one(query[key]); nodelist.push_back(query[key]); query[key]->value = value; return; } NODE* one = new NODE(key, value); if (count >= capacity){ NODE* dropped = nodelist.head; nodelist.delete_one(nodelist.head); nodelist.push_back(one); query[key] = one; query.erase(dropped->key); } else { count++; nodelist.push_back(one); query[key] = one; } } }; /** * 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); */
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步