Skip to content

Instantly share code, notes, and snippets.

@AtomicVar
Last active February 29, 2024 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AtomicVar/ac046d72f08bb5fc56e6b0b75cfe4cb8 to your computer and use it in GitHub Desktop.
Save AtomicVar/ac046d72f08bb5fc56e6b0b75cfe4cb8 to your computer and use it in GitHub Desktop.
A simple LRU Cache in C++ STL.
#include <list>
#include <unordered_map>
#include <utility>
using namespace std;
class LRUCache {
size_t capacity;
list<pair<int, int>> dlist;
using ListIt = decltype(dlist)::iterator;
unordered_map<int, ListIt> hash_map;
void add_to_head(int key, int value) {
dlist.emplace_front(key, value);
hash_map[key] = dlist.begin();
}
void move_to_head(ListIt it) {
dlist.splice(dlist.begin(), dlist, it);
}
void remove_last() {
hash_map.erase(dlist.back().first);
dlist.pop_back();
}
public:
LRUCache(int capacity) : capacity(capacity) {}
int get(int key) {
if (hash_map.count(key) == 0) {
return -1;
}
ListIt it = hash_map[key];
move_to_head(it);
return it->second;
}
void put(int key, int value) {
if (hash_map.count(key)) {
ListIt it = hash_map[key];
move_to_head(it);
it->second = value;
} else {
add_to_head(key, value);
if (dlist.size() > capacity) {
remove_last();
}
}
}
};
@AtomicVar
Copy link
Author

Verify it with LeetCode: LRU Cache - LeetCode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment