力扣打卡5:LRU缓存

链接:146. LRU 缓存 - 力扣(LeetCode)

这道题我解法的put函数严格意义上讲不是O(1),不如力扣官方的题解。

我使用了哈希表存储值,这样每次get就可以O(1)了。但是put不太好优化成O(1),我使用了一个队列和一个哈希表来实现它。通过记录一个数据的使用次数存在哈希表,数据存储顺序放在queue,来实现这个put。但是如果capacity满了,每次put会弹出不定数的数据。虽然每次的次数基本会很少.但是在极端情况下会是O(n-capacity)。

我很喜欢官方题解的方式,他使用了一个哈希表和一个双向链表,并将它们组合成一个新的数据结构,哈希表key为数据的索引,value是链表结点的指针,链表中存放数据。通过指针,将两个容器连接起来。get可以利用哈希表的性质实现快速查询,put可以利用双端链表的特性,可以灵活的将对应结点移到队首,将队尾的删除。

我的方法:

cpp 复制代码
class LRUCache {
public:

    unordered_map<int,int> cache;
    unordered_map<int,int> update;
    queue<int> q;
    int cap=0;
    int n=0;
    
    LRUCache(int capacity) {
        cap=capacity;
    }
    
    int get(int key) {
        if(cache.find(key)!=cache.end())
        {
            if(update.find(key)!=cache.end()) update[key]++;
            else update[key]=1;
            q.push(key);
            return cache[key];
        }
        return -1;
    }
    
    void put(int key, int value) {
        if(cache.find(key)!=cache.end())
        {
            cache[key]=value;
            if(update.find(key)!=cache.end()) update[key]++;
            else update[key]=1;
            q.push(key);
        }
        else if(++n<=cap)
        {
            cache[key]=value;
            if(update.find(key)!=cache.end()) update[key]++;
            else update[key]=1;
            q.push(key);
        }
        else
        {
            n--;
            cache[key]=value;
            if(update.find(key)!=cache.end()) update[key]++;
            else update[key]=1;
            q.push(key);
            while(1)
            {
                int t=q.front();
                q.pop();
                if(update[t]<=1)
                {
                    update[t]--;
                    cache.erase(t);
                    return;
                }
                update[t]--;
            }
        }
    }
};
相关推荐
Evand J7 小时前
【MATLAB例程】三维RRT+APF路径规划与AOA-TDOA融合定位算法。附代码的下载链接
算法·matlab·路径规划·rrt·tdoa·apf·aoa
海绵宝宝转agent7 小时前
leetCode100算法开源笔记分享
笔记·算法
写后端的胖头鱼8 小时前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
hahaha60168 小时前
黑体轨迹和色温--光源白点
人工智能·嵌入式硬件·算法·计算机视觉
海绵宝宝转agent8 小时前
基于Redis ZSet+AOP+注解实现限流注解算法
数据库·redis·算法
imDwAaY8 小时前
Redis 也能做消息队列?从 Stream 的存储讲到消费确认
数据库·redis·缓存
All for pursuit.9 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
白杨尚青9 小时前
C++入门篇(十三):vector(上)——动态数组:构造、空间增长与迭代器失效
开发语言·c++·笔记·算法·stl
Jasmine_llq9 小时前
《P17461 [GESP202609 八级] 生成树计数》
算法·栈·tarjan 算法·边双连通分量·深度优先搜索 dfs·tarjan 保存当前路径节点·模乘法
Jasmine_llq9 小时前
《P17462 [GESP202609 八级] 末班车》
算法·dijkstra 算法·最大化版本,求最长可行值·建反向图(逆图 / 反转边)·多源 dijkstra 思想·对每个终点单独跑一遍djst·离线预处理 + 在线查询