leetcode:LRU Cache

本文详细介绍了LRU缓存算法的实现过程,包括双向链表和哈希表的结合使用,以及如何在缓存已满时移除最久未使用的元素。通过get和set操作,有效地管理了缓存容量,确保了高效的数据访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

LRU缓存算法实现,这个算法就是在缓存已满时,将最久未使用的元素移出缓存。
经典实现就是双向链表加哈希,每次使用(get or set)都使用哈希值找到这个元素在双链表中的位置,然后将它移到最前面,如果缓存已满就删除队尾的元素。哈希中放的是元素的地址,在新增、移动和删除元素的时候都要在Hash表中作对应修改,而双向链表主要是为了方便删除。

class Node{
public:
    int key, val;
    Node *pre, *next;
    Node(int k, int v): key(k), val(v), pre(NULL), next(NULL) {}
};
class LRUCache{
    map<int, Node*> mp;
    map<int, Node*>::iterator iter;
    int used, cap;
    Node *head, *tail;
public:
    LRUCache(int capacity) {
        mp.clear();
        used = 0, cap = capacity;
        head = new Node(0, 0);
        tail = new Node(0, 0);
        head->next = tail, tail->pre = head;
    }
    ~LRUCache(){
        for (Node *n = head, *nnext; n; n = nnext) {
            nnext = n->next;
            delete n;
        }
    }

    int get(int key) {
        if ((iter = mp.find(key)) != mp.end()) {
            movetoFirst(iter->second);
            return iter->second->val;
        }else
            return -1;
    }

    void set(int key, int value) {
        if ((iter = mp.find(key)) != mp.end()) {
            iter->second->val = value;
            movetoFirst(iter->second);
        } else {
            Node *node;
            if (used == cap) {
                mp.erase(tail->pre->key);
                node = tail->pre;
                node->key = key, node->val = value;
            } else {
                node = new Node(key, value);
                used++;
            }
            mp[node->key] = node;
            movetoFirst(node);
        }
    }
    void movetoFirst(Node *node) {
        if (node->pre && node->next) {
            node->pre->next = node->next;
            node->next->pre = node->pre;
        }
        node->pre = head, node->next = head->next;
        head->next->pre = node, head->next = node;
    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值