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;
        }
    }
 }
};
相关推荐
椰羊~王小美4 分钟前
LeetCode -- Flora -- edit 2025-04-27
算法·leetcode·职场和发展
流影ng1 小时前
C语言HashTable基本理解
c语言·哈希算法
观无5 小时前
Redis远程链接应用案例
数据库·redis·缓存·c#
星星点点洲5 小时前
【缓存与数据库结合方案】伪从技术 vs 直接同步/MQ方案的深度对比
数据库·缓存
mit6.8246 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表
好想有猫猫7 小时前
【Redis】服务端高并发分布式结构演进之路
数据库·c++·redis·分布式·缓存
vim怎么退出9 小时前
43.验证二叉搜索树
前端·leetcode
爱的叹息9 小时前
MyBatis缓存配置的完整示例,包含一级缓存、二级缓存、自定义缓存策略等核心场景,并附详细注释和总结表格
缓存·mybatis
山猪打不过家猪10 小时前
(六)RestAPI 毛子(外部导入打卡/游标分页/Refit/Http resilience/批量提交/Quartz后台任务/Hateoas Driven)
网络·缓存
编程绿豆侠10 小时前
力扣HOT100之链表:23. 合并 K 个升序链表
算法·leetcode·链表