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;
        }
    }
 }
};
相关推荐
czlczl200209258 小时前
缓存穿透问题与解决方案
缓存·mybatis
YGGP10 小时前
【Golang】LeetCode 128. 最长连续序列
leetcode
陌上丨16 小时前
Redis的Key和Value的设计原则有哪些?
数据库·redis·缓存
月挽清风17 小时前
代码随想录第十五天
数据结构·算法·leetcode
时艰.19 小时前
Java 并发编程 — 并发容器 + CPU 缓存 + Disruptor
java·开发语言·缓存
TracyCoder12320 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
惊讶的猫21 小时前
Redis持久化介绍
数据库·redis·缓存
We་ct21 小时前
LeetCode 56. 合并区间:区间重叠问题的核心解法与代码解析
前端·算法·leetcode·typescript
生产队队长1 天前
Redis:Windows环境安装Redis,并将 Redis 进程注册为服务
数据库·redis·缓存
努力学算法的蒟蒻1 天前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展