knakul853

Untitled

Jul 20th, 2020
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. class LRUCache {
  2. public:
  3.    
  4.     LRUCache(int capacity) {
  5.        
  6.         sz = capacity;
  7.     }
  8.    
  9.     int get(int key) {
  10.                
  11.         auto it = cache.find(key);
  12.         if( it == cache.end()) return -1;
  13.         touch(it);
  14.         return it->second.first;
  15.        
  16.     }
  17.  
  18.     void put(int key, int value) {
  19.        
  20.         auto it = cache.find(key);
  21.         if(it != cache.end()) touch(it);
  22.         else{
  23.             if(sz == (int)q.size())
  24.             {
  25.                 cache.erase(q.back());
  26.                 q.pop_back();
  27.             }
  28.            
  29.             q.push_front(key);
  30.         }
  31.      cache[key] = {value, q.begin()};
  32.  
  33.        
  34.     }
  35.    
  36.     private:
  37.     typedef list<int>li;
  38.     typedef pair<int, li::iterator>pii;
  39.     typedef unordered_map<int, pii>ump;
  40.    
  41.     ump cache;
  42.     li q;
  43.     int sz;
  44.    
  45.     void touch(ump::iterator it )
  46.     {
  47.         q.erase(it->second.second);
  48.         q.push_front(it->first);
  49.         it->second.second = q.begin();
  50.     }
  51.    
  52. };
  53.  
  54. /**
  55.   knakul853
  56.  */
Add Comment
Please, Sign In to add comment