题解 | #设计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);
 */

解题思路:使用双端队列

全部评论

相关推荐

10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务