-
Notifications
You must be signed in to change notification settings - Fork 0
/
146_lru-cache.cpp
95 lines (82 loc) · 2.16 KB
/
146_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
//
// Created by 71401 on 2021/7/20.
//
/**
* 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);
*/
#include <vector>
#include <unordered_map>
struct DLinkedNode {
int key, value;
DLinkedNode *prev, *next;
DLinkedNode() : key(0), value(0), prev(nullptr), next(nullptr) {}
DLinkedNode(int _key, int _value) : key(_key), value(_value), prev(nullptr), next(nullptr) {}
};
class LRUCache {
private:
unordered_map<int, DLinkedNode *> cache;
DLinkedNode *head;
DLinkedNode *tail;
int curr_size;
int capacity;
protected:
void addToHead(DLinkedNode *node) {
node->prev = head;
node->next = head->next;
head->next->prev = node;
head->next = node;
}
void removeNode(DLinkedNode *node) {
node->prev->next = node->next;
node->next->prev = node->prev;
}
void moveToHead(DLinkedNode *node) {
removeNode(node);
addToHead(node);
}
void checkSize() {
if (this->curr_size > this->capacity) {
DLinkedNode *victim = tail->prev;
cache.erase(victim->key);
removeNode(victim);
delete victim;
this->curr_size--;
}
}
public:
LRUCache(int capacity) {
head = new DLinkedNode();
tail = new DLinkedNode();
head->next = tail;
tail->prev = head;
this->curr_size = 0;
this->capacity = capacity;
}
int get(int key) {
if (!cache.count(key)) {
return -1;
}
DLinkedNode *node = cache[key];
moveToHead(node);
return node->value;
}
void put(int key, int value) {
// if already exists in the cache
if (cache.count(key)) {
DLinkedNode *node = cache[key];
node->value = value;
moveToHead(node);
}
// not exist
else {
DLinkedNode *newNode = new DLinkedNode(key, value);
cache[key] = newNode;
addToHead(newNode);
curr_size++;
checkSize();
}
}
};