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;
        }
    }
 }
};
相关推荐
吃着火锅x唱着歌2 分钟前
LeetCode 74.搜索二维矩阵
算法·leetcode·矩阵
羊锦磊17 分钟前
[ Redis ] SpringBoot集成使用Redis(补充)
java·数据库·spring boot·redis·spring·缓存·json
williamdsy1 小时前
【清除 Mac DNS 缓存】Mac 电脑能访问外网却无法加载特定页面?你的 DNS 缓存“发霉”了!
macos·缓存
linff9112 小时前
hot 100 技巧题
数据结构·算法·leetcode
奎歪歪5 小时前
UniApp缓存系统详解
缓存·uni-app·1024程序员节
Miraitowa_cheems6 小时前
LeetCode算法日记 - Day 84: 乘积为正数的最长子数组长度
数据结构·算法·leetcode·贪心算法·线性回归·深度优先·动态规划
en-route7 小时前
使用缓存版本号解决缓存一致性问题
缓存
xiaopengbc7 小时前
谷歌商店下载APK教程,先下载谷歌三件套,再直接从 Google Play 下载 APK 文件?
leetcode
儒道易行8 小时前
【攻防实战】Redis未授权RCE联动metasploit打穿三层内网(上)
数据库·redis·网络安全·缓存
TG_yunshuguoji9 小时前
亚马逊云渠道商:AWS 本地 SSD 缓存是什么?
缓存·云计算·aws