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;
        }
    }
 }
};
相关推荐
ofoxcoding5 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
想吃火锅10055 天前
【leetcode】121.买卖股票的最佳时机js/c++
算法·leetcode·职场和发展
NeilYuen5 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans5 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
凌波粒5 天前
LeetCode--491.递增子序列(回溯算法)
数据结构·算法·leetcode
退休倒计时5 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚5 天前
Linux——Redis
数据库·redis·缓存
小欣加油5 天前
leetcode3612 用特殊操作处理字符串I
数据结构·c++·算法·leetcode·职场和发展
凌波粒5 天前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode