这一题要我们设计一个LRU(最近最少使用算法),我的思路是用一个hash表加一个双向链表实现,其插入,删除,获取节点时间复杂度均在O(1),代码如下
class LRUCache {
public:
struct node {
int key;
int val;
node* front;
node* next;
node() : val(0), front(NULL), next(NULL) {};
node(int value, int Key) :val(value), key(Key), front(NULL), next(NULL) {};
};
LRUCache(int capacity) {
maxsize = capacity;
head = new node();
tail = new node();
head->next = tail;
tail->front = head;
}
int get(int key) {
if (!m.count(key) || maxsize == 0) return -1;
node& n = m[key];
visied(n);
return n.val;
}
void put(int key, int value) {
if (maxsize == 0) return;
m[key].val = value;
m[key].key = key;
visied(m[key]);
if (m.size()>maxsize)
pop();
}
void visied(node& n) {
if (n.front)
n.front->next = n.next;
if (n.next)
n.next->front = n.front;
n.next = head->next;
head->next->front = &n;
head->next = &n;
n.front = head;
}
void pop() {
node* temp = tail->front;
tail->front = temp->front;
temp->front->next = tail;
m.erase(temp->key);
}
private:
int size;
int maxsize;
node* head;
node* tail;
unordered_map<int, node> m;
};