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

设计LRU缓存结构

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

哈希表:管理存在的数据

双向链表:管理数据的优先级。使用双向链表的原因是要进行头插入、尾删除和删除中间某个节点。

class Node {
public:
    int key_, val_;
    Node *pre_, *next_;
    Node(int key, int val, Node *pre = nullptr, Node *next = nullptr)
    : key_(key), val_(val), pre_(pre), next_(next) {}
};

class Solution {
    int size;
    Node *head, *tail;
    unordered_map<int, Node*> umap;
public:
    Solution(int capacity)
    : head(new Node(-1, -1)), tail(new Node(-1, -1)) {
        size = capacity;
        head->next_ = tail;
        tail->pre_ = head;
    }

    void movetohead(Node *node) {
        if(node->pre_ == head) return;
        if(node->pre_) node->pre_->next_ = node->next_;
        if(node->next_) node->next_->pre_ = node->pre_;

        node->pre_ = head;
        node->next_ = head->next_;
        head->next_->pre_ = node;
        head->next_ = node;
    }

    int get(int key) {
        auto it = umap.begin();
        if((it = umap.find(key)) == umap.end()) return -1;
        movetohead(it->second);
        return it->second->val_;
    }

    void set(int key, int value){
        auto it = umap.begin();
        if((it = umap.find(key)) != umap.end()) {
            it->second->val_ = value;
            movetohead(it->second);
        } else {
            Node *newnode = new Node(key, value);
            movetohead(newnode);
            umap[key] = newnode;
            if(size > 0) size--;
            else {
                Node *temp = tail->pre_;
                cout << temp->val_ << endl;
                tail->pre_ = temp->pre_;
                temp->pre_->next_ = tail;
                umap.erase(temp->key_);
                delete temp;
            }
        }
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:32
点赞 评论 收藏
分享
仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
zzzzhz:兄弟你先猛猛投简历至少三百家,能约到面试就去面。最近可以速成智能小车,智慧家居烂大街的项目,不需要自己写,只需要把里面的代码讲解看明白就行。把其中涉及到的八股文都拿出来单独背一下,我去年找工作就一个智能小车智慧家居找了10k差不多。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:45
你不要过来啊啊啊啊啊啊啊
码农索隆:对面:“今天你不面也得面”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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