标签:ret oid 记录 city called 存在 anti obj 使用
1 class LRUCache { 2 private: 3 struct ListNode{ 4 int key,val; 5 ListNode *pre; 6 ListNode *next; 7 ListNode(int x, int y) : key(x), val(y), pre(NULL), next(NULL){} 8 }; 9 ListNode *head, *tail; 10 unordered_map<int, ListNode*> i2lmap; 11 int cap; 12 13 void remove(ListNode* node){ 14 if(node==head) 15 head = head->next; 16 if(node==tail) 17 tail = tail->pre; 18 if(node->pre) 19 node->pre->next=node->next; 20 if(node->next) 21 node->next->pre=node->pre; 22 i2lmap.erase(node->key); 23 delete node; 24 } 25 26 void insert(int key, int value){ 27 ListNode *node = new ListNode(key, value); 28 if(!head){ 29 head=tail=node; 30 } 31 else{ 32 tail->next=node; 33 node->pre=tail; 34 tail=node; 35 } 36 i2lmap[key]=node; 37 } 38 39 public: 40 LRUCache(int capacity) { 41 cap = capacity; 42 head=tail=NULL; 43 } 44 45 int get(int key) { 46 if(i2lmap.find(key)==i2lmap.end()) 47 return -1; 48 49 int value = i2lmap[key]->val; 50 remove(i2lmap[key]); 51 insert(key, value); 52 return value; 53 } 54 55 void put(int key, int value) { 56 if(i2lmap.find(key)!=i2lmap.end()) 57 remove(i2lmap[key]); 58 else if(i2lmap.size() == cap) 59 remove(head); 60 insert(key, value); 61 } 62 }; 63 64 /** 65 * Your LRUCache object will be instantiated and called as such: 66 * LRUCache* obj = new LRUCache(capacity); 67 * int param_1 = obj->get(key); 68 * obj->put(key,value); 69 */
用一个哈希表和双向链表来实现。
哈希表记录节点是否存在,并计数
双向链表实现按优先级删除和添加。链表头为长时间未使用的低优先级,链表尾为最近使用的高优先级。
标签:ret oid 记录 city called 存在 anti obj 使用
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/11695544.html