spider68

LRU cache

Jul 18th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. class LRUCache {
  2. public:
  3.     int size;
  4.     list<int> lru;                              // MRU ... LRU
  5.     unordered_map<int, list<int>::iterator> mp; // key -> iterator
  6.     unordered_map<int, int> kv;
  7.     LRUCache(int capacity) : size(capacity) {}
  8.    
  9.     int get(int key) {
  10.         if (kv.count(key) == 0) return -1;
  11.         updateLRU(key);
  12.         return kv[key];
  13.     }
  14.    
  15.     void put(int key, int value) {
  16.         if (kv.size() == size && kv.count(key) == 0)evict();
  17.         updateLRU(key);
  18.         kv[key] = value;
  19.     }
  20.     void updateLRU(int key) {
  21.         if (kv.count(key))lru.erase(mp[key]);
  22.         lru.push_front(key);
  23.         mp[key] = lru.begin();
  24.     }
  25.     void evict() {
  26.         mp.erase(lru.back());
  27.         kv.erase(lru.back());
  28.         lru.pop_back();
  29.     }
  30. };
Add Comment
Please, Sign In to add comment