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;
        }
    }
 }
};
相关推荐
文丑颜不良啊6 小时前
LeetCode3041~3060题目解析
java·leetcode
文丑颜不良啊7 小时前
LeetCode3101~3120题目解析
java·leetcode
牢姐与蒯12 小时前
cpp算法之哈希
c++·算法·哈希算法
玄昌盛不会编程15 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊15 小时前
LeetCode3061~3080题目解析
java·leetcode
CappuccinoRose16 小时前
Redis 学习文档
redis·后端·学习·缓存·session·非关系型数据库·gossip
web安全成长日记17 小时前
DNS解析全过程:从递归查询、根域与权威 DNS 到缓存 TTL|网络安全其实很简单
安全·web安全·缓存
时间的拾荒人17 小时前
Redis 典型应用:缓存与分布式锁原理
redis·分布式·缓存·面试·架构
文丑颜不良啊18 小时前
LeetCode3081~3100题目解析
java·leetcode