题解 | #设计LRU缓存结构#

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

哈希表:利用查找O(1)特性,用于记录key对应的键值对在链表中的位置,用指针表示。

双向链表:利用插入和删除操作的O(1)特性。用于模拟缓存,当哈希表给出了操作的位置,就可以直接调整链表结点的指针从而实现O(1)的插入和删除。

class Solution {
  private:
    int capacity;
    unordered_map<int, list<pair<int, int>>::iterator> hash; //{key=iterator}
    list<pair<int, int>> cache; //{"1"="1","2"="2"}
  public:
    Solution(int capacity) {
        this->capacity = capacity;
    }

    int get(int key) {
        if (hash.find(key) != hash.end()) {
            auto kv = hash[key];
            cache.erase(hash[key]);
            cache.push_front(*kv);
            return (*kv).second;
        } else {
            return -1;
        }
    }

    void set(int key, int value) {
        if (hash.find(key) == hash.end()) {
            if (cache.size() == capacity) {
                hash.erase(cache.back().first);
                cache.pop_back();
            }
        } else {
            cache.erase(hash[key]);
        }
        cache.push_front({key, value});
        hash[key] = cache.begin();
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* solution = new Solution(capacity);
 * int output = solution->get(key);
 * solution->set(key,value);
 */

全部评论

相关推荐

11-17 11:15
门头沟学院 Java
金山办公终于发offer了,但薪资和平台都不如已有的offer打算拒了,A不了薪资,不满意直接拒了,留给需要的人嘿嘿嘿时间线:10.14线下一面&nbsp;,10.23线上二面,下午发测评,11月1日HR面,11月14日电话谈薪,11月17日直接发offer
star__plat...:好兄弟干的好啊,解气。金山第一次笔难度高的离谱,第二次简单的离谱全A了,用人部门筛选中估计最后还是要挂我,就这今早智联招聘还给我发信息让我投
offer帮选
点赞 评论 收藏
分享
肖先生~:那年秋招闯进一位少年,人们都清楚:成功对他来说只是时间问题
点赞 评论 收藏
分享
10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务