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;
        }
    }
 }
};
相关推荐
tkevinjd1 小时前
图论\dp 两题
leetcode·动态规划·图论
1白天的黑夜15 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼355 小时前
力扣子集问题C++代码
c++·算法·leetcode
熬了夜的程序员5 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
Miraitowa_cheems5 小时前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
jakeswang6 小时前
应用缓存不止是Redis!——亿级流量系统架构设计系列
redis·分布式·后端·缓存
.Shu.8 小时前
Redis zset 渐进式rehash 实现原理、触发条件、执行流程以及数据一致性保障机制【分步源码解析】
数据库·redis·缓存
Mi_Manchikkk8 小时前
Java高级面试实战:Spring Boot微服务与Redis缓存整合案例解析
java·spring boot·redis·缓存·微服务·面试
无聊的小坏坏20 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学