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

设计LRU缓存结构

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

#include <deque>
class Solution {
public:
    Solution(int capacity){
         // write code here
        maxsize = capacity;
        cursize = 0;
    }
    
    int get(int key) {
        // write code here
        int res = -1;
        for(auto beg = q.begin();beg != q.end();++beg)
        {
            if(beg->first == key)
            {
                res = beg->second;
                q.erase(beg);
                q.push_front({key,res});
                break;
            }
        }
        return res;
    }
    
    void set(int key, int value){
         // write code here
        if(cursize >= maxsize)
        {
            q.pop_back();
            cursize--;
        }        
        q.push_front({key,value});
        cursize++;
    }
private:
    int maxsize;
    int cursize;
    deque<pair<int,int>> q;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* solution = new Solution(capacity);
 * int output = solution->get(key);
 * solution->set(key,value);
 */

解题思路:使用双端队列

全部评论

相关推荐

03-29 15:34
门头沟学院 Java
北斗导航Compass低仿版:能不能先搞清楚优先级啊,怎么可能是项目问题,项目很重要吗?又没学历 又没实习大厂凭啥约面?那玩具项目 没应用在真实生产环境下的 就算做上天又有什么用?早点找个小公司实习 拿小公司实习去投大厂实习,这才是你现在该做的
投递美团等公司8个岗位 简历被挂麻了,求建议
点赞 评论 收藏
分享
03-16 22:00
武汉大学 C++
幸福的小熊猫想要offer:我阿里投的 c++岗,面试官说自己是做 java 的,c++这辈子才有了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务