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;
        }
    }
 }
};
相关推荐
Hello.Reader2 小时前
RedisJSON 路径语法深度解析与实战
数据库·redis·缓存
千宇宙航7 小时前
闲庭信步使用图像验证平台加速FPGA的开发:第十课——图像gamma矫正的FPGA实现
图像处理·计算机视觉·缓存·fpga开发
Alfred king9 小时前
面试150 LRU缓存
链表·缓存·哈希表·lru·双向链表
愚润求学10 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
岸边的风12 小时前
退出登录后头像还在?这个缓存问题坑过多少前端!
前端·缓存·状态模式
Liudef0612 小时前
大模型KV缓存量化误差补偿机制:提升推理效率的关键技术
人工智能·缓存
在未来等你12 小时前
Redis面试精讲 Day 1:Redis核心特性与应用场景
数据库·redis·缓存·nosql·面试准备
dying_man12 小时前
LeetCode--44.通配符匹配
算法·leetcode
Paper Clouds13 小时前
代码随想录|图论|15并查集理论基础
数据结构·算法·leetcode·深度优先·图论
GGBondlctrl14 小时前
【leetcode】字符串,链表的进位加法与乘法
算法·leetcode·链表·字符串相加·链表相加·字符串相乘