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;
        }
    }
 }
};
相关推荐
升鲜宝供应链及收银系统源代码服务2 小时前
升鲜宝生鲜配送供应链管理系统---PMS--商品品牌多语言存储与 Redis 缓存同步实现
java·开发语言·数据库·redis·缓存·开源·供应链系统
sin_hielo2 小时前
leetcode 1611
算法·leetcode
来荔枝一大筐3 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
苦学编程的谢3 小时前
Redis_8_List
数据库·redis·缓存
一个不称职的程序猿4 小时前
高并发场景下的缓存利器
java·缓存
小白程序员成长日记4 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白4 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小白程序员成长日记5 小时前
2025.11.08 力扣每日一题
算法·leetcode·职场和发展
他们叫我一代大侠7 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
java1234_小锋8 小时前
REDIS集群会有写操作丢失吗?为什么
数据库·redis·缓存