zoukankan      html  css  js  c++  java
  • LC 146. LRU Cache

    link

    class LRUCache {
    public:
        int cap;
        int size;
        unordered_map<int,int> ktov; // key to value
        unordered_map<int,list<int>::iterator> ktoi; // key to iterator
        list<int> li;
        
        LRUCache(int capacity) {
            cap=capacity;
            size=0;
        }
        
        int get(int key) {
            if(ktov.find(key)==ktov.end()) return -1;
            li.erase(ktoi[key]);
            li.push_back(key);
            ktoi[key]=--li.end();
            return ktov[key];
        }
        
        void put(int key, int value) {
            if(ktov.find(key)!=ktov.end()){
                ktov[key]=value;
                li.erase(ktoi[key]);
                li.push_back(key);
                ktoi[key]=--li.end();
            }else{
                if(size>=cap){
                    --size;
                    int del=li.front();
                    li.pop_front();
                    ktov.erase(del);
                    ktoi.erase(del);
                }
                li.push_back(key);
                ktov[key]=value;
                ktoi[key]=--li.end();
                ++size;
            }
        }
    };
    
    /**
     * Your LRUCache object will be instantiated and called as such:
     * LRUCache* obj = new LRUCache(capacity);
     * int param_1 = obj->get(key);
     * obj->put(key,value);
     */
  • 相关阅读:
    Go 映射 (map)
    Go 字节 (byte) & 文字符号 (rune)
    Go 数组(array) & 切片(slice)
    Go 字符串 (string)
    Go 变量(var) & 常量(const)
    Go 循环 (for)
    Go 函数
    Go package: strings
    Linux crontab (定时任务)
    Python gc
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12436297.html
Copyright © 2011-2022 走看看