zoukankan      html  css  js  c++  java
  • LeetCode "LRU Cache"

    1A. It is a design problem actually. It tests your ability to connect your knowledge of data structures & algorithms, with real world problems.

    class LRUCache{
    private:
        deque<int> q; // by key
        unordered_map<int, int> hash;
        int _capacity;
    public:
        LRUCache(int capacity) {
            _capacity = capacity;
        }
        
        int get(int key) {
            if (hash.find(key) != hash.end())
            {
                //    Update queue
                auto it = std::find(q.begin(), q.end(), key);
                q.erase(it);
                q.push_back(key);
                //
                return hash[key];
            }
            return -1;
        }
        
        void set(int key, int value) {
            if (hash.find(key) != hash.end())
            {
                //    Update queue
                auto it = std::find(q.begin(), q.end(), key);
                q.erase(it);
                q.push_back(key);
            }
            else
            {
                if(q.size() < _capacity)
                {
                    q.push_back(key);
                }
                else
                {
                    //    Invalidate LRU
                    int okey = q.front();
                    q.pop_front();
                    hash.erase(okey);
                    q.push_back(key);
                }
            }
            hash[key] = value;
        }
    };
  • 相关阅读:
    docker安装部署命令
    kubernetes原理
    kubernetes安装部署
    Ansible安装
    模拟红绿灯(递归与队列)
    数据结构——顺序表
    数据结构——基本概念
    C语言高级编程
    Shell编程
    Shell命令
  • 原文地址:https://www.cnblogs.com/tonix/p/3911655.html
Copyright © 2011-2022 走看看