Skip to content

Commit 5aa54ed

Browse files
authored
Created LRU_Cache.cpp
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
1 parent bd19832 commit 5aa54ed

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

146. LRU Cache/LRU_Cache.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
2+
3+
struct Node {
4+
int key;
5+
int value;
6+
Node(int key, int value) : key(key), value(value) {}
7+
};
8+
9+
10+
class LRUCache {
11+
public:
12+
LRUCache(int capacity) : capacity(capacity) {}
13+
14+
int get(int key) {
15+
if (!keyToIterator.count(key))
16+
return -1;
17+
18+
const auto& it = keyToIterator[key];
19+
// move it to the front
20+
cache.splice(begin(cache), cache, it);
21+
return it->value;
22+
}
23+
24+
void put(int key, int value) {
25+
// no capacity issue, just update the value
26+
if (keyToIterator.count(key)) {
27+
const auto& it = keyToIterator[key];
28+
// move it to the front
29+
cache.splice(begin(cache), cache, it);
30+
it->value = value;
31+
return;
32+
}
33+
34+
// check the capacity
35+
if (cache.size() == capacity) {
36+
const auto& lastNode = cache.back();
37+
// that's why we store `key` in `Node`
38+
keyToIterator.erase(lastNode.key);
39+
cache.pop_back();
40+
}
41+
42+
cache.emplace_front(key, value);
43+
keyToIterator[key] = begin(cache);
44+
}
45+
46+
private:
47+
const int capacity;
48+
list<Node> cache;
49+
unordered_map<int, list<Node>::iterator> keyToIterator;
50+
};
51+

0 commit comments

Comments
 (0)