剑指 Offer II 031. 最近最少使用缓存

题目

力扣

思路

创建一个新的数据结构,双向链表。从头结点插入新的数据,从尾节点删除数据。通过缓存数据的键映射到其在双向链表中的位置。为了在添加节点和删除节点时避免检查相邻的节点是否存在,可以使用一个伪头部和伪尾部来标记界限。

代码

class LRUCache {
public:
    struct Node{
        int key,value;
        Node* prev;
        Node* next;
        Node():key(0),value(0),prev(nullptr),next(nullptr){}
        Node(int _key,int _value):key(_key),value(_value),prev(nullptr),next(nullptr){}
    };
    Node *head,*tail;
    int size=0,capacity;
    unordered_map<int,Node*> map;
    LRUCache(int _capacity) {
        capacity = _capacity;
        head = new Node();
        tail = new Node();
        head->next=tail;
        tail->prev=head;
    }

    void addtoHead(Node* cur){
        cur->next=head->next;
        head->next->prev=cur;
        head->next=cur;
        cur->prev=head;
    }

    void removeNode(Node* cur){
        cur->next->prev=cur->prev;
        cur->prev->next=cur->next;
    }

    void movetoHead(Node* cur){
        removeNode(cur);
        addtoHead(cur);
    }
    
    int get(int key) {
        if(!map.count(key)) return -1;
        Node* cur=map[key];
        movetoHead(cur);
        return map[key]->value;
    }
    
    void put(int key, int value) {
        if(map.count(key)){
            map[key]->value=value;
            movetoHead(map[key]);
        }
        else{
            Node* cur=new Node(key,value);
            map[key]=cur;
            addtoHead(cur);
            if(++size>capacity){
                map.erase(tail->prev->key);
                tail->prev=tail->prev->prev;
                tail->prev->next=tail;
                size--;
            }
        }
        return;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值