Last active
February 29, 2024 06:59
-
-
Save ZJUGuoShuai/ac046d72f08bb5fc56e6b0b75cfe4cb8 to your computer and use it in GitHub Desktop.
A simple LRU Cache in C++ STL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Verify it with LeetCode: LRU Cache - LeetCode.