Advertisement
leoanjos

LRU Cache

Apr 22nd, 2022
1,008
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. class LRUCache {
  2. private:
  3.     int cap;
  4.     unordered_map<int, int> values, cnt;
  5.     queue<int> order;
  6.    
  7. public:
  8.     LRUCache(int capacity) {
  9.         cap = capacity;
  10.     }
  11.    
  12.     int get(int key) {
  13.         if (values.count(key) == 0)
  14.             return -1;
  15.        
  16.         cnt[key]++;
  17.         order.push(key);
  18.         return values[key];
  19.     }
  20.    
  21.     void put(int key, int value) {
  22.         if ((int) values.size() >= cap && values.count(key) == 0) {
  23.             while (cnt[order.front()] > 1) {
  24.                 cnt[order.front()]--;
  25.                 order.pop();
  26.             }
  27.            
  28.             cnt[order.front()]--;
  29.             values.erase(order.front());
  30.             order.pop();
  31.         }
  32.        
  33.         cnt[key]++;
  34.         order.push(key);
  35.         values[key] = value;
  36.     }
  37. };
  38.  
  39. /**
  40.  * Your LRUCache object will be instantiated and called as such:
  41.  * LRUCache* obj = new LRUCache(capacity);
  42.  * int param_1 = obj->get(key);
  43.  * obj->put(key,value);
  44.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement