forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0146-lru-cache.cpp
100 lines (82 loc) · 2.16 KB
/
0146-lru-cache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Design data structure that follows constraints of an LRU cache
Hash map + doubly linked list, left = LRU, right = MRU
get: update to MRU, put: update to MRU, remove LRU if full
Time: O(1)
Space: O(capacity)
*/
class Node {
public:
int k;
int val;
Node* prev;
Node* next;
Node(int key, int value) {
k = key;
val = value;
prev = NULL;
next = NULL;
}
};
class LRUCache {
public:
LRUCache(int capacity) {
cap = capacity;
left = new Node(0, 0);
right = new Node(0, 0);
left->next = right;
right->prev = left;
}
int get(int key) {
if (cache.find(key) != cache.end()) {
remove(cache[key]);
insert(cache[key]);
return cache[key]->val;
}
return -1;
}
void put(int key, int value) {
if (cache.find(key) != cache.end()) {
remove(cache[key]);
// Free allocated memory for the removed node
delete cache[key];
}
cache[key] = new Node(key, value);
insert(cache[key]);
if (cache.size() > cap) {
// remove from list & delete LRU from map
Node* lru = left->next;
remove(lru);
cache.erase(lru->k);
// Free allocated memory for the removed node
delete lru;
}
}
private:
int cap;
unordered_map<int, Node*> cache; // {key -> node}
Node* left;
Node* right;
// remove node from list
void remove(Node* node) {
Node* prev = node->prev;
Node* next = node->next;
prev->next = next;
next->prev = prev;
}
// insert node at right
void insert(Node* node) {
Node* prev = right->prev;
Node* next = right;
prev->next = node;
next->prev = node;
node->prev = prev;
node->next = next;
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/