Grind 75 - Leetcode146 LRU缓存

Leetcode146 LRU缓存

经典题,典型compund data structure思想
link
思路

  • 主要思想就是hash table + double-linked list
  • 重点就是手动实现这些功能
  • 因为getput都要求 O ( 1 ) O(1) O(1)时间内实现,所以就是要用hash table
  • 而要实现LRU,所以用双向链表维护最近使用

ps: code 多打几遍就熟悉了

class Node {
public:
    int key;
    int value;
    Node *last, *next;
    Node(int k = 0, int val = 0) : key(k), value(val), last(nullptr), next(nullptr) {}
};

class LRUCache {
private:
    unordered_map<int, Node*> cache;
    int size;
    int capacity;
    Node *head;
    Node *tail;

    void addNode(Node *node) {
        node->next = head->next;
        head->next->last = node;
        node->last = head;
        head->next = node;
    }

    void deleteNode(Node *node) {
        node->last->next = node->next;
        node->next->last = node->last;
    }

    void move(Node *node) {
        deleteNode(node);
        addNode(node);
    }

    Node *deleteTail() {
        Node *node = tail->last;
        deleteNode(node);
        return node;
    }

public:
    LRUCache(int capacity) : capacity(capacity), size(0) {
        head = new Node();
        tail = new Node();
        head->next = tail;
        tail->last = head;
    }
    
    int get(int key) {
        if (cache.count(key) == 0)
            return -1;
        Node *node = cache[key];
        move(node);
        return node->value;
    }
    
    void put(int key, int value) {
        if (cache.count(key) > 0) {
            Node *node = cache[key];
            node->value = value;
            move(node);
        }
        else {
            Node *node = new Node(key, value);
            cache[key] = node;
            addNode(node);
            ++size;
            if (size > capacity) {
                Node *lastUsed = deleteTail();
                cache.erase(lastUsed->key);
                --size;
                delete lastUsed;
            }
        }
    }
};
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值