1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class LRUCache { public: LRUCache(int capacity) : capacity(capacity) {
}
int get(int key) { if (!cache.count(key)) return -1; auto it = cache[key]; history.splice(begin(history), history, it); return it->second; }
void put(int key, int value) { if (cache.count(key)) { auto it = cache[key]; history.splice(begin(history), history, it); it->second = value; return; } if (capacity == size(cache)) { auto key_to_delete = history.back().first; history.pop_back(); cache.erase(key_to_delete); } cache[key] = history.emplace(begin(history), key, value); }
unordered_map<int, list<pair<int, int>>::iterator> cache; list<pair<int, int>> history; int capacity; };
|