leetcode-设计LRU缓存结构-112

题目要求

思路

双链表+哈希表
代码实现

cpp 复制代码
struct Node{
    int key, val;
    Node* next;
    Node* pre;
    Node(int _key, int _val): key(_key), val(_val), next(nullptr), pre(nullptr){}
};

class Solution {
public:
unordered_map<int, Node*> hash;
Node* head;
Node* tail;
int cap;
int size;

 Solution(int capacity){
    size = 0;
    cap = capacity;
    head = nullptr;
    tail = nullptr;
    hash.clear();
 }
 
void removetohead(Node* p)
{
    if(p == head)
        return;
    p->pre->next = p->next;
    if(p == tail)
        tail = p->pre;
    else
        p->next->pre = p->pre;
    p->next = head;
    p->pre = nullptr;
    head->pre = p;
    head = p;
    return;
}

 int get(int key) {
    if(hash.find(key) == hash.end())
        return -1;
    removetohead(hash[key]);
    return hash[key]->val;
 }
 
 void set(int key, int val){
    if(hash.find(key) != hash.end())
    {
        hash[key]->val = val;
        removetohead(hash[key]);
    }
    else {
        if(size < cap) {
            Node* p = new Node(key, val);
            if(head == nullptr)
                head = tail = p;
            else {
                head->pre = p;
                p->next = head;
                head = p;
            }
            hash[key] = head;
            size++;
        }
        else{
            int k = tail->key;
            hash.erase(k);
            tail->key = key;
            tail->val = val;
            removetohead(tail);
            hash[key] = head;
        }
    }
 }
};
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
-Xie-2 天前
Mysql杂志(十六)——缓存池
数据库·mysql·缓存
七夜zippoe2 天前
缓存与数据库一致性实战手册:从故障修复到架构演进
数据库·缓存·架构
weixin_456904272 天前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
元亓亓亓2 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
仙俊红2 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
MarkHard1232 天前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
心想事成的幸运大王2 天前
Redis的过期策略
数据库·redis·缓存
_不会dp不改名_2 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
wuyunhang1234562 天前
Redis---集群模式
数据库·redis·缓存