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

设计LRU缓存结构

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

用 map 和 链表来组织结构

struct node{
        int key, val;
        node* pre;
        node* next;
        node(int k, int v): key(k), val(v), pre(nullptr), next(nullptr){};
    };

class Solution {
private:
    unordered_map<int, node*> mp;
    int cnt = 0;
    vector<int> res;
    node* head;
    node* tail;
    int size;
    int cap;
public:
    /**
     * lru design
     * @param operators int整型vector<vector<>> the ops
     * @param k int整型 the k
     * @return int整型vector
     */
    
    vector<int> LRU(vector<vector<int> >& operators, int k) {
        // write code here
        head = new node(0, 0);
        tail = new node(0, 0);
        head->next = tail;
        tail->pre = head;
        size = 0;
        cap = k;
        for(vector<int> op : operators){
            if(op[0] == 1){
                set(op[1], op[2]);
            }
            if(op[0] == 2){
                int value = get(op[1]);
                res.push_back(value);
                
            }
        }
        return res;
        
    }
    int get(int key){
        if(!mp.count(key)){
            return -1;
        }
        node* tmp = mp[key];
        movetohead(tmp);
        return tmp->val;
    }
    void set(int key, int val){
        if(!mp.count(key)){
            node* tar = new node(key, val);
            mp[key] = tar;
            addtohead(tar);
            ++size;
            if(size > cap){
                node* remo = removetail();
                mp.erase(remo->key);
                delete remo;
                --size;
            }
        }else{
            node* tar = mp[key];
            tar->val = val;
            movetohead(tar);
        }
        
    }
    void movetohead(node* tmp){
        removenode(tmp);
        addtohead(tmp);
    }
    void removenode(node* tmp){
        tmp->pre->next = tmp->next;
        tmp->next->pre = tmp->pre;
    }
    void addtohead(node* tmp){
        tmp->next = head->next;
        tmp->pre = head;
        head->next->pre = tmp;
        head->next = tmp;
    }
    node* removetail(){
        node* tmp = tail->pre;
        removenode(tmp);
        return tmp;
    }
};
全部评论

相关推荐

04-06 11:24
已编辑
太原学院 C++
点赞 评论 收藏
分享
02-25 23:53
门头沟学院 Java
神哥不得了:神哥来啦~自我评价和校园经历的话可以直接删了,从大厂暑期的话应该没有什么太多问题,应该是能拿到很多大厂面试机会的,就是在面试的时候表示的好一点就行,可以在面试前先把高频top 50的八股多巩固几遍,千万不要看那些假高频八股,这两个项目的话问题不是很大,应该能够帮你找到大厂实习的,算法的话一定要刷起来,因为大厂有些还是比较看重算法的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务