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;
        }
    }
 }
};
相关推荐
Sylus_sui21 分钟前
git中如何从某次历史提交节点上创建一个新的分支
git·算法·哈希算法
一条大祥脚30 分钟前
25.12.30
数据库·redis·缓存
falldeep1 小时前
Pandas入门指南
数据结构·算法·leetcode·pandas
闲看云起1 小时前
Leetcode-day4:从「移动零」到「盛最多水的容器」
数据结构·算法·leetcode·职场和发展
圣保罗的大教堂2 小时前
leetcode 840. 矩阵中的幻方 中等
leetcode
sin_hielo3 小时前
leetcode 840
数据结构·算法·leetcode
十八岁讨厌编程5 小时前
【算法训练营 · 补充】LeetCode Hot100(下)
算法·leetcode·职场和发展
攻心的子乐5 小时前
redis 使用Pipelined 管道命令批量操作 减少网络操作次数
数据库·redis·缓存
Channon_6 小时前
专题四:内存战场的无声战役——压缩、共享与空间复用
缓存·嵌入式·空间复用