题解 | 设计LRU缓存结构 C++/简单STL

设计LRU缓存结构

https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84

class Solution {
private:
int cap;
map<int,int> mp;
list<int> ls;

public:
 Solution(int capacity){
    cap = capacity;
 }
 
 void updateList(int key) {
    if (!mp[key]) {
        ls.push_front(key);
    } else {
        for(auto it = ls.begin();it!=ls.end();it++) {
            if (*it == key) {
                ls.erase(it);
                break;
            }
        }
        ls.push_front(key);
    }
    if(ls.size()>cap) {
        int dlkey = ls.back();
        mp.erase(dlkey);
        ls.pop_back();
    }
 }

 int get(int key) {
    if (mp.count(key)) {
        updateList(key);
        return mp[key];
    }
    else {
        return -1;
    }
 }
 
 void set(int key, int value){
    mp[key] = value;
    updateList(key);
 }
};

全部评论

相关推荐

米哈游校招进主页喵:大佬 考虑我司不 考虑的话可以看我主页帖子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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