C++ List+哈希表实现,无需实现链表的操作

设计LRU缓存结构

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

哈希表保存key到Node的映射,list维护双向链表,代码简练

class Solution {
public:
    /**
     * lru design
     * @param operators int整型vector<vector<>> the ops
     * @param k int整型 the k
     * @return int整型vector
     */
    struct Node {
        int key;
        int val;
        Node(int k, int v) : key(k), val(v) {}
    };
    unordered_map<int, Node*> mp;
    list<Node*> sorted_list;
    int max_size = 0;
    void set(int key, int value) {
        Node* node = new Node(key, value);
        // 链表满了,需要删除元素
        if(sorted_list.size() == max_size) {
            //删除链表尾结点和哈希表映射
            Node* tmp = sorted_list.back();
            mp.erase(tmp->key);
            sorted_list.pop_back();
        }
        mp[key] = node;
        sorted_list.push_front(node);
    }
    int get(int key) {
        if(mp.count(key)) {
            // 访问过,把节点提到最前
            Node* cur = mp[key];
            sorted_list.remove(cur);
            sorted_list.push_front(cur);
            return cur->val;
        }
        return -1;
    }
    vector<int> LRU(vector<vector<int> >& operators, int k) {
        // write code here
        vector<int> res;
        max_size = k;
        for(vector<int>& op : operators) {
            if(op[0] == 1) {
                set(op[1], op[2]);
            }
            else if(op[0] == 2) {
                //cout << get(op[1]) << endl;
                res.push_back(get(op[1]));
            }
        }
        return res;
    }
};
全部评论

相关推荐

2025-12-28 16:32
重庆邮电大学 Java
程序员花海:1.技能放最后,来面试默认你都会,技能没啥用 2.实习写的看起来没啥含金量,多读读部门文档,包装下 接LLM这个没含金量 也不要用重构这种 不会给实习生做的 3.抽奖这个还是Demo项目,实际在公司里面要考虑策略,满减,触发点,触发规则 库存 之类的,不是这个项目这么简单 4.教育背景提前,格式为 教育背景 实习 项目 技能 自我评价
简历被挂麻了,求建议
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务