diff --git a/LRU Cache/LRUCache.cpp b/LRU Cache/LRUCache.cpp new file mode 100644 index 0000000..77dc5e2 --- /dev/null +++ b/LRU Cache/LRUCache.cpp @@ -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 recent; + unordered_map cache; + unordered_map::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(); + } +};