Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions LRU Cache/LRUCache.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class LRUCache {
public:
LRUCache(int capacity) {
this->capacity = capacity;
}

int get(int key) {
if(cache.find(key) != cache.end())
{
use(key);
return cache[key];
}
return -1;
}

void put(int key, int value) {
use(key);
cache[key] = value;
}

private:
int capacity;
list<int> recent;
unordered_map<int,int> cache;
unordered_map<int, list<int>::iterator> pos;

void use(int key)
{
if(pos.find(key) != pos.end())
{
recent.erase(pos[key]);
}
else if(recent.size() >= capacity)
{
int old = recent.back();
recent.pop_back();
cache.erase(old);
pos.erase(old);
}
recent.push_front(key);
pos[key] = recent.begin();
}
};