双链表实现LRU

题目:
LRU 缓存机制 设计和实现一个 LRU(最近最少使用)缓存数据结构,使它应该支持一下操作:get 和 put。

  1. get(key) - 如果 key 存在于缓存中,则获取 key 的 value(总是正数),否则返回 -1。
  2. put(key,value) - 如果 key 不存在,请设置或插入 value。当缓存达到其容量时,它应该在插入新项目之前使最近最少使用的项目作废。
#include <unordered_map>

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


class Solution {
    
    
private:
    int size = 0;
    DListNode* head;
    DListNode* tail;
    unordered_map<int, DListNode*> mp;

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
        if(k < 1) return {
    
    };
        this->size = k;
        this->head = new DListNode(0,0);
        this->tail = new DListNode(0,0);
        this->head->next = this->tail;
        this->tail->pre = this->head;

        if(operators.size() == 0) return {
    
    };

        vector<int> res;

        for(vector<int> op : operators){
    
    
            if(op[0] == 1) {
    
    
                set(op[1], op[2]);
            }
            else if(op[0] == 2){
    
    
                int value = get(op[1]);
                res.push_back(value);
            }
        }
        return res;
    }

    void set(int key, int val){
    
    
        if(mp.find(key) == mp.end()){
    
     // hashmap 中没找到
            DListNode* node = new DListNode(key, val);
            mp[key] = node;
            if(this->size <= 0){
    
    
                removeLast();
            }
            else{
    
    
                this->size--;
            }
            insertFirst(node);
        }
        else{
    
      // hashmap 中已经有了,也就是链表里也已经有了
            mp[key]->val = val;
            moveToHead(mp[key]);
        }
    }


    int get(int key){
    
    
        int ret = -1;
        if(mp.find(key) != mp.end()){
    
    
            ret = mp[key]->val;
            moveToHead(mp[key]);
        }
        return ret;
    }

    void moveToHead(DListNode* node){
    
    
        if(node->pre == this->head) return;
        node->pre->next = node->next;
        node->next->pre = node->pre;
        insertFirst(node);
    }


    void removeLast(){
    
    
        mp.erase(this->tail->pre->key);
        this->tail->pre->pre->next = this->tail; // remove the last node in dlist
        this->tail->pre = this->tail->pre->pre;
    }

    void insertFirst(DListNode* node){
    
    
        node->pre = this->head;
        node->next = this->head->next;
        this->head->next->pre = node;
        this->head->next = node;
    }

};

猜你喜欢

转载自blog.csdn.net/weixin_43202635/article/details/111602883