The
designs and implements a LRU (least recently used) cache data structure so that it should support the following operations: Get and put.
Get (Key)-if the key exists in the cache, gets the value of the key (always a positive number), otherwise returns-1.
put (key, value)-If the key does not exist, set or insert a value. When the cache reaches its capacity, it should invalidate the least recently used items before inserting new items.
Follow up:
Can you do two things in the O (1) time complexity?
Case:
LRUCache cache = new LRUCache (2 */capacity */);
Cache.put (1, 1);
Cache.put (2, 2);
Cache.get (1); //return 1
cache.put (3, 3); //The operation will Key 2 void
Cache.get (2); //Return-1 (result not present)
Cache.put (4, 4); / /This operation will invalidate key 1
Cache.get (1); //Return-1 (result does not exist)
Cache.get (3); & nbsp; //Return 3
Cache.get (4); //return 4
See: HTTPS ://leetcode.com/problems/lru-cache/description/
Class LRUCache {public: LRUCache (int capacity) { cap=capacity; } int get (int key) { auto It=m.find (key); if (It==m.end ()) { return-1; } L.splice (L.begin (), l,it->second); Return it->second->second; } void put (int key, int value) { auto It=m.find (key); if (It!=m.end ()) { l.erase (it->second); } L.push_front (Make_pair (Key,value)); M[key]=l.begin (); if (L.size () >cap) { Auto K=l.rbegin ()->first; L.pop_back (); M.erase (k); } } Private: int cap; List<pair<int,int>> l; Unordered_map<int,list<pair<int,int>>::iterator> m;};/ * * Your LRUCache object would be instantiated and called as such: * LRUCache obj = new LRUCache (capacity); * int param_1 = Obj.get (key); * Obj.put (Key,value); */
146 LRU Cache Least Recently used page replacement algorithm