LC-146-LRU 缓存

77 篇文章 1 订阅
63 篇文章 0 订阅
文章介绍了使用双向链表和unordered_map数据结构实现LRU缓存的思路。当访问到键时,会将该节点移动到链表尾部;如果需要替换,会替换链表头部的节点。时间复杂度为O(1)。代码中定义了一个LRUCache类,包含添加、更新、获取和放置键值对的方法。
摘要由CSDN通过智能技术生成

原题链接:LRU 缓存

个人解法

思路:

用双向链表维护LRU中的key和value,若访问到则将对应的结点置换到链表尾部,若需要替换则直接替换链表头部,这个比较难debug,要注意细节。

时间复杂度: O ( 1 ) O(1) O(1)

代码:

class LRUCache {
public:
    struct Node {
        int key, value;
        Node *next;
        Node *prev;
    };

    Node *head;
    Node *tail;
    int capacity;
    unordered_map<int, Node *> mp;

    LRUCache(int capacity) {
        this->head = new Node();
        this->head->next = nullptr;
        this->head->prev = nullptr;
        this->tail = head;
        this->capacity = capacity;
    }

    void add(int key, int value) {
        tail->next = new Node();
        Node *t = tail;
        tail = tail->next;
        tail->key = key, tail->value = value, tail->prev = t;
        tail->next = nullptr;
        mp[key] = tail;
    }

    void update(int key) {
        if(mp.count(key)) {
            Node *p = mp[key];
            if(p == tail) return;
            p->prev->next = p->next;
            p->next->prev = p->prev;
            tail->next = p;
            p->prev = tail;
            tail = tail->next;
            tail->next = nullptr;
        }
    }
    
    int get(int key) {
        update(key);
        if(mp.count(key)) return mp[key]->value;
        return -1;
    }
    
    void put(int key, int value) {
        update(key);
        if(mp.count(key)) mp[key]->value = value;
        else if(capacity) {
            add(key, value);
            -- capacity;
        }else {
            add(key,value);
            Node *t = head;
            head = head->next;
            mp.erase(head->key);
            delete t;
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值