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.
Idea: LRU here involves the use of vectors to record memory address, using map mapping key and the corresponding key in the vector mapping, the first is always the latest, if the memory is not used up, use the new memory, if used, from the first memory update, and then put the initial memory in the last block, It is important to note that the map information is needed here.
Class Lrucache{public:lrucache (int capacity) {m_capacity=capacity; m_size = 0; for (int i=0;i<capacity;i++) {int* temp = (int*) malloc (sizeof (int)); *temp = 0; M_cache.push_back (temp); }} int get (int key) {Map<int,int>::iterator itr=m_hash.find (key); if (ITR = = M_hash.end ()) return-1; else return * (M_cache[itr->second]); } void set (int key, int value) {Map<int,int>::iterator itr=m_hash.find (key); Map<int,int>::iterator index; if (ITR = = M_hash.end ())//not found {if (M_size < m_capacity) {*m_cache[m_size] = V Alue; M_hash.insert (pair<int,int> (key,m_size)); m_size++; } else {for (Index=m_hash.begin (); Index!=m_hash.end (); index++) if (index-> ; second ==0)ITR = index; else index->second--; M_hash.erase (ITR); int* temp = m_cache[0]; M_cache.erase (M_cache.begin ()); *temp = value; M_cache.push_back (temp); M_hash.insert (Pair<int,int> (Key,m_cache.size ()-1)); }} else {int* temp = m_cache[itr->second]; *m_cache[itr->second] = value; M_cache.erase (M_cache.begin () +itr->second); M_cache.push_back (temp); For (Index=m_hash.begin (); Index! = M_hash.end (); index++) if (Index->second > Itr->second) index->second--; Itr->second = M_cache.size ()-1; }} ~lrucache () {for (Int. i=0;i<m_capacity;i++) Free (m_cache[i]); } Private:int m_capacity; int m_size; Vector<int*> M_cache; Map<int,int> M_hash;};
LRU Cache--leetcode