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

设计LRU缓存结构

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

class Solution {
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
        // 使用list来维护LRU缓存
        // 使用哈希表提高查询速度
        list<pair<int, int>> lru_list;
        unordered_map<int, list<pair<int, int>>::iterator> mil; // 直接存储list的迭代器,减少list的查询
        vector<int> res;
        
        // 使用新特性auto
        for (auto op : operators) {
            // set or get
            switch(op[0]) {
                // set
                case 1: {
                    // 插入一个值,这个值可能出现过也可能没有出现过
                    auto it = mil.find(op[1]);
                    if (it != mil.end()) { // 已经在缓存中
                        // 删除list中原来的节点,插入新节点到最前面
                        lru_list.erase(it->second);
                        // 再set新值在最前面
                        lru_list.push_front(make_pair(op[1], op[2]));
                        // 更改map为对应的list节点
                        it->second = lru_list.begin();
                    } else { // 没有在缓存中
                        // 缓存以满,需要先删除最后的节点
                        if (lru_list.size() == k) {
                            // map也要删除
                            mil.erase(lru_list.back().first);
                            lru_list.pop_back();
                        }
                        // 新节点加入
                        lru_list.push_front(make_pair(op[1], op[2]));
                        mil.insert({op[1], lru_list.begin()});
                    }
                } break;
                // get
                case 2: {
                    auto it = mil.find(op[1]);
                    if (it != mil.end()) {
                        // 在缓存中,查找结果加入res中
                        int num = it->second->second;
                        res.push_back(num);
                        // 更新缓存位置
                        lru_list.erase(it->second);
                        lru_list.push_front(make_pair(op[1], num));
                        // 更新map
                        it->second = lru_list.begin();
                    } else {
                        res.push_back(-1);
                    }
                } break;
            }
        }
        return res;
        
    }
};
全部评论

相关推荐

但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
05-14 09:24
青岛工学院 C++
点赞 评论 收藏
分享
05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
看到这个内容真是闹麻了。。。。。。现在有了AI以后很多人面试都会作弊吗?&nbsp;那对老老实实面试的人岂不是不公平....
程序员牛肉:公平那是对小孩子讲的童话故事,成年人的世界只有能不能接受失败的后果。 你要是能接受面试作弊被发现之后多家公司联合永久拉黑的后果,你就搞。
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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