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

设计LRU缓存结构

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

class LinkNode{

public:

int key;
int val;
LinkNode * pNext;
LinkNode * pPre;

LinkNode(int key, int val){
    this->key = key;
    this->val = val;
    pNext = NULL;
    pPre = NULL;
}

};


class Solution{



public:

/**
 * lru design
 * @param operators int整型vector<vector<>> the ops
 * @param k int整型 the k
 * @return int整型vector
 */

Solution(){
    head = new LinkNode(0, 0);
    tail = new LinkNode(0, 0);
    head->pNext = tail;
    tail->pNext = head;
}


vector<int> LRU(vector<vector<int> >& operators, int k) {
    // write code here
    this->capaticy = k;
    vector<int> ret;
    if(operators.empty()) return ret;

    for(int i = 0; i<operators.size(); i++){
        //cout<<nodeMap.size()<<i <<endl;
        int opt = operators.at(i)[0];
        if(opt == 1){
            int key = operators.at(i)[1];
            int val = operators.at(i)[2];
            Put(key,  val);
        }
        else if(opt == 2){
            int valRet = Get(operators.at(i)[1]);
            ret.push_back(valRet);
        }
    }

    return ret;
}

void Add(LinkNode *node){
    node->pPre = head;
    node->pNext = head->pNext;
    head->pNext->pPre = node;
    head->pNext = node;
}

void Remove(LinkNode *node){
    node->pPre->pNext = node->pNext;
    node->pNext->pPre = node->pPre;
}

void UpDate(LinkNode *node){
    Remove(node);
    Add(node);
}

int Get(int key){
    LinkNode * node = nodeMap[key];
    if(!node) return -1;

    UpDate(node);
    return node->val;
}

void Put(int key, int val){
    LinkNode *node = nodeMap[key];

    // 没有找到就放到头部后面
    if(!node) {
        node = new LinkNode(key, val);
        Add( node);
        nodeMap[key] = node;
        this->currCount++;
    }else{
        node->val = val;
        UpDate(node);
    }

    // 超容,删除尾部节点
    if(this->currCount > this->capaticy){
        LinkNode * node = tail->pPre;

        LinkNode * pre = tail->pPre->pPre;
        pre->pNext = tail;
        tail->pPre = pre;

        nodeMap.erase(node->key);
        free(node);
        this->currCount--;
    }
}


private:

int capaticy;
int currCount = 0;
LinkNode *head;
LinkNode *tail;
map<int, LinkNode*> nodeMap ;

};
全部评论

相关推荐

11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
狠赚笔第一人:学计算机自己不努力怪大环境?我大一就拿到了美团大厂的offer,好好看看自己有没有努力查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务