LRU缓存数据结构的设计

请你设计并实现一个满足  LRU (最近最少使用) 缓存 约束的数据结构。

实现 LRUCache 类:

  • LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  • void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。

函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

示例:

输入
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1);    // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2);    // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1);    // 返回 -1 (未找到)
lRUCache.get(3);    // 返回 3
lRUCache.get(4);    // 返回 4

一:以下使用双链表和哈希表进行构建LRU缓存,链表用来记录缓存访问的顺序,越在链表头,说明访问时间越接近当前时间。进行了一次查询,说明也是访问了一次缓存,需要记录一下key,更新链表。而哈希表的key是查询key,而value记录的是链表数据的pair迭代器,从而能很方便找到value。值在链表里面,哈希表是为了快速找到链表的位置,因为链表随机插入和删除效率很高,查询效率不高,所以用哈希表来帮助查询key。

class LRUCache {

public:

    LRUCache(int capacity) {

        m_capacity=capacity;

    }

   

    int get(int key) {

        auto it = m_cacheMap.find(key);

        if(it !=m_cacheMap.end() ){

            m_cacheList.splice(m_cacheList.begin(),m_cacheList,it->second);

            return it->second->second;

        }

        return -1;

    }

   

    void put(int key, int value) {

        auto it = m_cacheMap.find(key);

        if(it != m_cacheMap.end()){

            //说明现在存在key,需要换一下value

            it->second->second =value;

            m_cacheList.splice(m_cacheList.begin(),m_cacheList,it->second);

        }

        else{ if(m_cacheList.size()==m_capacity){

                int keyToRemove = m_cacheList.back().first;

                //缓存已经满了,需要删除哈希表和链表,通过链表最后面的key删除哈希表

                m_cacheMap.erase(keyToRemove);

                m_cacheList.pop_back();

        }

            // 缓存没有满,加入哈希表和链表中

          m_cacheList.emplace_front(key, value); // 加入链表头部,链表先进后才有哈希表记录value

            m_cacheMap[key] = m_cacheList.begin(); //哈希表的key键插入value值

        }

    }

private:

    int m_capacity;

    list<pair<int,int>> m_cacheList;

    unordered_map<int,list<pair<int,int>>::iterator> m_cacheMap;

   

};

/**

 * 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);

 */

二.一下是用单链表进行记录缓存的一种方式。

#include <iostream>
#include <unordered_map>

class LRUCache {
public:
    LRUCache(int capacity) : m_capacity(capacity), m_head(nullptr) {}

    int get(int key) {
        auto it = m_cacheMap.find(key);
        if (it != m_cacheMap.end()) {
            moveToHead(it->second);
            return it->second->value;
        }
        return -1;
    }

    void put(int key, int value) {
        auto it = m_cacheMap.find(key);
        if (it != m_cacheMap.end()) {
            it->second->value = value;
            moveToHead(it->second);
        } else {
            if (m_cacheMap.size() == m_capacity) {
                removeTail();
            }
            insertToHead(key, value);
        }
    }

private:
    struct Node {
        int key;
        int value;
        Node* next;
        Node(int k, int v) : key(k), value(v), next(nullptr) {}
    };

    int m_capacity;
    std::unordered_map<int, Node*> m_cacheMap;
    Node* m_head;

    void moveToHead(Node* node) {
        // 移动节点到链表头部
        if (node != m_head) {
            removeNode(node);
            insertToHead(node->key, node->value);
        }
    }

    void removeNode(Node* node) {
        // 从链表中删除节点
        if (node == nullptr) return;
        Node* current = m_head;
        while (current->next != node) {
            current = current->next;
        }
        current->next = node->next;
        m_cacheMap.erase(node->key);
        delete node;
    }

    void removeTail() {
        // 删除链表尾部节点
        if (m_head == nullptr) return;
        Node* current = m_head;
        Node* prev = nullptr;
        while (current->next != nullptr) {
            prev = current;
            current = current->next;
        }
        if (prev != nullptr) {
            prev->next = nullptr;
            m_cacheMap.erase(current->key);
            delete current;
        }
    }

    void insertToHead(int key, int value) {
        // 插入节点到链表头部
        Node* newNode = new Node(key, value);
        newNode->next = m_head;
        m_head = newNode;
        m_cacheMap[key] = newNode;
    }
};

int main() {
    // 示例用法
    LRUCache cache(2);

    cache.put(1, 1);
    cache.put(2, 2);
    std::cout << cache.get(1) << std::endl;  // 输出 1
    cache.put(3, 3);  // 移除 key 2
    std::cout << cache.get(2) << std::endl;  // 输出 -1,因为 key 2 不再存在于缓存中
    cache.put(4, 4);  // 移除 key 1
    std::cout << cache.get(1) << std::endl;  // 输出 -1,因为 key 1 不再存在于缓存中
    std::cout << cache.get(3) << std::endl;  // 输出 3
    std::cout << cache.get(4) << std::endl;  // 输出 4

    return 0;
}
 

  • 19
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值