Skip to content

Commit 020537a

Browse files
committed
feat: Add LRU cache
* Include "tests.h" in source files.
1 parent 6deafb3 commit 020537a

File tree

3 files changed

+88
-6
lines changed

3 files changed

+88
-6
lines changed

cpp/arrays/non-overlapping-intervals.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
* https://medium.com/swlh/non-overlapping-intervals-f0bce2dfc617
99
*/
1010

11-
#include <tests.h>
11+
#include "tests.h"
1212

1313
/* ===========================================================================
1414
* Algorithms implementation

cpp/bits/shift-gt-type-width.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,7 @@
88
* GCC produces warning and the output is logical 0.
99
*/
1010

11-
#include <bitset>
12-
#include <iomanip>
13-
#include <iostream>
14-
15-
using namespace std;
11+
#include "tests.h"
1612

1713
template <class T>
1814
constexpr bitset<sizeof(size_t) * 8> bits(T x)

cpp/dsa/lru_cache.cpp

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include "tests.h"
2+
3+
struct Node;
4+
using NodePtr = Node *;
5+
6+
struct Node {
7+
int key, value;
8+
NodePtr next, prev;
9+
10+
Node(int k, int v) : key(k), value(v), next(nullptr), prev(nullptr) {}
11+
};
12+
13+
inline NodePtr new_node(int k, int v) { return new Node(k, v); }
14+
15+
class LRUCache
16+
{
17+
public:
18+
LRUCache(int c) : cap(c)
19+
{
20+
head = new_node(-1, -1);
21+
tail = new_node(-1, -1);
22+
head->next = tail;
23+
tail->prev = head;
24+
}
25+
26+
int get(int key)
27+
{
28+
if (m.contains(key)) {
29+
NodePtr node = m[key];
30+
int ans = node->value;
31+
m.erase(key);
32+
deleteNode(node);
33+
addToFront(node);
34+
m[key] = getFrontNode();
35+
return ans;
36+
}
37+
return -1;
38+
}
39+
40+
void put(int key, int value)
41+
{
42+
if (m.contains(key)) {
43+
NodePtr node = m[key];
44+
m.erase(key);
45+
deleteNode(node);
46+
}
47+
if (m.size() == cap) {
48+
NodePtr node = getRearNode();
49+
m.erase(node->key);
50+
deleteNode(node);
51+
}
52+
addToFront(new_node(key, value));
53+
m[key] = getFrontNode();
54+
}
55+
56+
private:
57+
void addToFront(NodePtr node)
58+
{
59+
NodePtr t = head->next;
60+
node->next = t;
61+
node->prev = head;
62+
head->next = node;
63+
t->prev = node;
64+
}
65+
66+
void deleteNode(NodePtr node)
67+
{
68+
NodePtr p = node->prev;
69+
NodePtr n = node->next;
70+
p->next = n;
71+
n->prev = p;
72+
}
73+
74+
NodePtr getFrontNode(void) const { return head->next; }
75+
NodePtr getRearNode(void) const { return tail->prev; }
76+
77+
size_t cap;
78+
unordered_map<int, NodePtr> m;
79+
NodePtr head, tail; // anchor nodes
80+
};
81+
82+
int main(int, char **)
83+
{
84+
cout << "Executed 1 implementations with 1 tests." << endl;
85+
return 0;
86+
}

0 commit comments

Comments
 (0)