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;
        }
    }
 }
};
相关推荐
Nil2082 小时前
leetcode 98验证二叉搜索树
算法·leetcode·职场和发展
时针滴滴答啊6 小时前
最大子数组和
算法·leetcode·职场和发展
重生之后端学习7 小时前
15. 三数之和[中等]✅
java·数据结构·算法·leetcode·职场和发展
Nil2088 小时前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
hn小菜鸡9 小时前
LeetCode 763、划分字母区间
数据结构·算法·leetcode
疯狂打码的少年10 小时前
【数据结构】哈希表:构造与冲突处理
数据结构·笔记·哈希算法·散列表
quantdash_cc10 小时前
历史数据断层与REST请求慢到崩溃?QuantDash高性能量化数据API终极解决方案
开发语言·python·缓存·php·量化·quantdash
一次旅行10 小时前
2026‑08‑22 AI产业深度解读|Anthropic自研芯片布局、SGLang权重缓存守护进程、Agent任务作弊审计、AI原生SDLC
人工智能·缓存·sglang
土司大王10 小时前
LeetCode hot100——相交链表
算法·leetcode·链表
土司大王10 小时前
LeetCode hot100——回文链表
算法·leetcode·链表