题解 | #设计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);
 */

全部评论

相关推荐

07-11 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:22
怎么这么多逆天求职者,救救我救救我救救我😭
flmz_Kk:哈哈哈哈哈哈,这么多求职者,肯定有那一两个逆天的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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