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

设计LRU缓存结构

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

C++ 哈希表,易理解

class Solution {
public:
    /**
     * lru design
     * @param operators int整型vector<vector<>> the ops
     * @param k int整型 the k
     * @return int整型vector
     */
    struct Node
    {
        int key,val;
        Node *left, *right;
        Node(int _key, int _val):key(_key),val(_val),left(NULL),right(NULL){}
    }*L,*R;

    int n;
    unordered_map<int, Node*> hash;

    void InitLRU(int capacity)
    {
        n = capacity;
        L = new Node(-1,-1);
        R = new Node(-1,-1);
        L->right = R;
        R->left = L;
    }

    void remove(Node *p)
    {
        // p 在 p->left 和 p->right 之间
        p->right->left = p->left;
        p->left->right = p->right;
    }

    void insert(Node *p)
    {
        //  L 和 L->right 之间插入 p
        p->right = L->right;
        p->left = L;
        L->right->left = p;
        L->right = p;
    }

    int get(int key)
    {
        if (hash.count(key) == 0)
            return -1;
        auto p = hash[key];
        remove(p);
        insert(p);
        return p->val;
    }

    void set(int key, int value)
    {
        if (hash.count(key))
        {
            auto p = hash[key];
            remove(p);
            insert(p);
            p->val = value;
        }
        else
        {
            if (hash.size() == n)
            {
                auto p = R->left;
                remove(p);
                hash.erase(p->key);
                delete p;
            }
            auto p = new Node(key, value);
            insert(p);
            hash[key] = p;
        }

    }

    vector<int> LRU(vector<vector<int> >& operators, int k) {
        vector<int> res;
        InitLRU(k);

        for (int i = 0; i < operators.size(); ++i)
        {
            if (operators[i][0] == 1)
                set(operators[i][1],operators[i][2]);
            else if (operators[i][0] == 2)
                res.push_back(get(operators[i][1]));
        }
        return res;
    }
};
全部评论

相关推荐

昨天 13:52
门头沟学院 后端
给🐭🐭个面试机会吧:嘿,mvbatis
点赞 评论 收藏
分享
暮雨轻歌:看起来hr不能接受我菜查看图片
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务