-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_16.25_LRUCache.cc
160 lines (143 loc) · 2.76 KB
/
Problem_16.25_LRUCache.cc
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
#include <cstdio>
#include <unordered_map>
#include <vector>
using namespace std;
class LRUCache
{
public:
LRUCache(int capacity) { cache = new MyCache<int, int>(capacity); }
int get(int key) { return cache->get(key); }
void put(int key, int value) { cache->set(key, value); }
template <typename K, typename V>
struct Node
{
K key;
V value;
Node* pre;
Node* next;
Node(K key, V value)
{
this->key = key;
this->value = value;
}
};
template <typename K, typename V>
class DoubleLikedList
{
private:
Node<K, V>* head;
Node<K, V>* tail;
public:
DoubleLikedList()
{
head = nullptr;
tail = nullptr;
}
void addNode(Node<K, V>* node)
{
if (node == nullptr)
{
return;
}
if (head == nullptr)
{
head = node;
tail = node;
}
else
{
tail->next = node;
node->pre = tail;
tail = node;
}
}
void moveNodeToTail(Node<K, V>* node)
{
if (node == tail)
{
return;
}
if (node == head)
{
head = head->next;
head->pre = nullptr;
}
else
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
node->pre = tail;
node->next = nullptr;
tail->next = node;
tail = node;
}
Node<K, V>* removeHead()
{
if (head == nullptr)
{
return nullptr;
}
Node<K, V>* ans = head;
if (head == tail)
{
head = nullptr;
tail = nullptr;
}
else
{
head = head->next;
ans->next = nullptr;
head->pre = nullptr;
}
return ans;
}
};
template <typename K, typename V>
class MyCache
{
public:
MyCache(int capacity) { this->capacity = capacity; }
void set(K key, V value)
{
if (map.count(key))
{
map[key]->value = value;
list.moveNodeToTail(map[key]);
}
else
{
if (capacity == map.size())
{
Node<K, V>* rm = list.removeHead();
map.erase(rm->key);
}
Node<K, V>* node = new Node<K, V>(key, value);
map[key] = node;
list.addNode(node);
}
}
V get(K key)
{
if (map.count(key))
{
list.moveNodeToTail(map[key]);
return map[key]->value;
}
return V(-1);
}
private:
unordered_map<K, Node<K, V>*> map;
// 双向非环形链表
DoubleLikedList<K, V> list;
int capacity;
};
private:
MyCache<int, int>* cache;
};
/**
* 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);
*/