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

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61

    int key, val;
    DListNode* pre;
    DListNode* nex;
    DListNode(int key, int val):key(key), val(val), pre(NULL), nex(NULL){};
};

class Solution {
public:
    /**
     * lru design
     * @param operators int整型vector<vector<>> the ops
     * @param k int整型 the k
     * @return int整型vector
     */
    int size = 0;
    DListNode* head;
    DListNode* tail;
    unordered_map<int, DListNode*> hash;
    vector<int> LRU(vector<vector<int> >& ops, int k) {
        // write code here
        this->size = k;
        this->head = new DListNode(0, 0);
        this->tail = new DListNode(0, 0);
        this->head->nex = this->tail;
        this->tail->pre = this->head;
        
        vector<int> res;
        if(ops.empty()) return res;  //进行判空校验
        for(auto op : ops){
            if(op[0] == 1){ //set操作
                set(op[1], op[2]);
            }else if(op[0] == 2){ //get操作
                res.push_back(get(op[1]));
            }
        }
        return res;
    }
    
    void set(int key, int val){
        if(hash.find(key) != hash.end()){
            //说明已经存在了key的节点,这时候只需要更新值即可
            hash[key]->val = val;
            move2Head(hash[key]);
        }else{
            //说明原先并无此节点,则进行创建
            DListNode* node = new DListNode(key, val);
            hash[key] = node;
            if(this->size <= 0){
                removeLast();
            }else this->size--;
            insertFirst(node);
        }
    }
    
    int get(int key){
        int ans = -1;
        if(hash.find(key) != hash.end()){
            ans = hash[key]->val;
            move2Head(hash[key]);
        }
        return ans;
    }
    
    void insertFirst(DListNode* node){
        node->pre = this->head;
        node->nex = this->head->nex;
        this->head->nex->pre = node;
        this->head->nex = node;
    }
    
    void move2Head(DListNode* node){
        if(node->pre == this->head) return;
        node->pre->nex = node->nex;
        node->nex->pre = node->pre;
        insertFirst(node);
    }
    
    void removeLast(){
        hash.erase(this->tail->pre->key);
        this->tail->pre->pre->nex = this->tail;
        this->tail->pre = this->tail->pre->pre;
    }
};
全部评论

相关推荐

预计下个星期就能开奖吧,哪位老哥来给个准信
华孝子爱信等:对接人上周说的是这周
点赞 评论 收藏
分享
11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
小红书 后端选手 n*16*1.18+签字费期权
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务