Skip to content

Commit

Permalink
Added LRU Cache
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 14, 2023
1 parent 1006fcc commit a91d22d
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -722,4 +722,15 @@ add_executable(PartitionList
target_link_libraries(
PartitionList
GTest::gtest_main
)

# LRU Cache
add_executable(LRUCache
Medium/LRUCache/include/solution.hpp
Medium/LRUCache/tests/test.cpp
)

target_link_libraries(
LRUCache
GTest::gtest_main
)
44 changes: 44 additions & 0 deletions Medium/LRUCache/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#pragma once

#include <list>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

class LRUCache {
public:
explicit LRUCache(std::size_t capacity) : _cache_size(capacity) { };

auto get(int32_t key) -> int32_t {
if (_pair.find(key) != _pair.end()) {
_doubly_list.splice(_doubly_list.begin(),
_doubly_list, _pair[key]);
return _pair[key]->second;
}

return -1;
}

auto put(int32_t key, int32_t value) -> void {
if (_pair.find(key) != _pair.end()) {
_pair[key]->second = value;
_doubly_list.splice(_doubly_list.begin(),
_doubly_list, _pair[key]);
return;
}

_doubly_list.emplace_front(key, value);
_pair[key] = _doubly_list.begin();

if (_doubly_list.size() > _cache_size) {
std::pair<int32_t, int32_t> &back = _doubly_list.back();
_pair.erase(back.first);
_doubly_list.pop_back();
}
}

private:
std::size_t _cache_size;
std::list<std::pair<int32_t, int32_t>> _doubly_list;
std::unordered_map<int32_t, std::list<std::pair<int32_t, int32_t>>::iterator> _pair;
};
17 changes: 17 additions & 0 deletions Medium/LRUCache/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include "../include/solution.hpp"

auto main() -> int {
auto *cache = new LRUCache(2);
cache->put(1, 1);
cache->put(2, 2);
std::cout << cache->get(1) << '\n';
cache->put(3, 3);
std::cout << cache->get(2) << '\n';
cache->put(4, 4);
std::cout << cache->get(1) << '\n';
std::cout << cache->get(3) << '\n';
std::cout << cache->get(4) << '\n';
delete cache;

return 0;
}

0 comments on commit a91d22d

Please sign in to comment.