Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)
- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
-------------------------------
双向链表 + unordered_map实现,有木有其他思路呢?
class LRUCache{
public:
LRUCache(int capacity) {
assert(capacity > 0);
cap = capacity;
cnt = 0;
head = tail = NULL;
nmap.clear();
}
int get(int key) {
if (nmap.count(key) == 0) return -1;
Node *node = nmap[key];
move2Head(node);
return node->value;
}
void set(int key, int value) {
if (nmap.count(key) > 0) {
updateNode(nmap[key], key, value);
return;
}
if (cnt < cap) {
createAndInsertNode(key, value);
return;
}
updateNode(tail, key, value);
}
private:
struct Node {
int key;
int value;
Node *prev, *next;
Node(int key, int value) : key(key), value(value), prev(NULL), next(NULL) {}
};
int cap;
int cnt;
unordered_map<int, Node*> nmap;
Node *head, *tail;
void move2Head(Node *node) {
if (node == NULL || node == head) return;
node->prev->next = node->next;
if (node->next != NULL) {
node->next->prev = node->prev;
} else {
tail = node->prev;
}
node->prev = NULL;
head->prev = node;
node->next = head;
head = node;
}
Node *createAndInsertNode(int key, int value) {
Node *node = new Node(key, value);
cnt++;
if (head == NULL) {
head = tail = node;
} else {
head->prev = node;
node->next = head;
head = node;
}
nmap[key] = node;
return node;
}
void updateNode(Node *node, int key, int value) {
if (node == NULL) return;
if (key != node->key) {
nmap.erase(node->key);
node->key = key;
nmap[key] = node;
}
node->value = value;
move2Head(node);
}
};