Design and implement a data structure for Least recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
-Get The value ('ll always be positive) of the key if the key exists in the cache, otherwise return-1.
set(key, value)
-Set or insert the value if the key is not already present. When the cache is reached its capacity, it should invalidate the least recently used item before inserting a new item.
Ideas:
1 classlrucache{2 Public:3 classdlist4 {5 Public:6Dlist *pre, *Next;7 intkey;8Dlist (intD, Dlist *p, Dlist *f): Key (d), Pre (P), next (f) {}9 };Ten intcap; OneDlist *front, *tail; Aunordered_map<int,int>data; -unordered_map<int, Dlist *>addr; -LRUCache (intcapacity) { theCap =capacity; -Front =NewDlist (0, NULL, NULL); -Tail =NewDlist (0, NULL, NULL); -Front->next =tail; +Tail->pre =Front; - } + A int Get(intkey) { at if(Data.count (key) = =0)return-1; - Delete (Addr[key]); - Addtotail (Addr[key]); - returnData[key]; - } - voidAddtotail (Dlist *node) in { -Tail->pre->next =node; toNode->pre = tail->Pre; +Node->next =tail; -Tail->pre =node; the } * voidDelete (Dlist *node) $ {Panax NotoginsengNode->pre->next = node->Next; -Node->next->pre = node->Pre; the } + void Set(intKeyintvalue) { A if(data.size () = = Cap && data.count (key) = =0) the { + if(Front->next = = tail)return; -Data.erase (front->next->key); $Addr.erase (front->next->key); $Delete (front->next); - } - if(Data.count (key) = =0) the { - Data.insert (Make_pair (key, value));WuyiDlist *ent =Newdlist (key, NULL, NULL); the Addr.insert (Make_pair (key, ENT)); - addtotail (ENT); Wu } - Else About { $Data[key] =value; - Delete (Addr[key]); - Addtotail (Addr[key]); - } A } +};
LRU Cache--Leetcode