解题思路
双链表+哈希:
双链表存储一个节点被使用(get或者put)的时间戳,且按最近使用时间从左到右排好序,最先被 使用的节点放在双链表的第一位,因此双链表的最后一位就是最久未被使用的节点
哈希表存储key对应的链表中的节点地址,用于key-value 的增删改查;
双链表和哈希表的增删改查操作的时间复杂度都是 O(1),所以get和put操作的时间复杂度也都是O(1)
代码
class LRUCache {
public:
//定义双链表
struct Node{
int key,value;//定义键值
Node* left, * right;//定义左右结点
Node(int _key,int _value):
key(_key),value(_value),left(NULL),right(NULL){ }
}*L,* R;//双链表的最左和最右节点,不存贮值
//定义无序哈希表
int n;
unordered_map<int, Node*>hash;
//链表删除结点
void remove(Node* p){
p->right->left = p->left;
p->left->right = p->right;
}
//链表插入结点
void insert(Node* p){
p->right = L->right;
p->left = L;
L->right->left = p;
L->right = p;
}
//以正整数作为容量 capacity 初始化 LRU 缓存
LRUCache(int capacity) {
n = capacity;
L = new Node(-1,-1), R = new Node(-1,-1);
L->right = R;
R->left = L;
}
//获取元素
int get(int key) {
if(hash.count(key) == 0) return -1;//不存在关键字
auto p = hash[key];
remove(p);
insert(p);//将当前操作过的节点放在链表头
return p->value;
}
//更新元素
void put(int key, int value) {
if(hash.count(key))//如果key存在,则修改对应的值
{
auto p = hash[key];
p->value = value;
remove(p);
insert(p);
}
else
{
if(hash.size() == n){//如果缓存已满,删除链表最右端的节点
auto p = R -> left;
remove(p);
hash.erase(p->key);//更新哈希表
delete p;//释放内存
}
//内存没满,直接插入
auto p = new Node(key,value);
hash[key] = p;
insert(p);
}
}
};
/**
* 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);
*/