阅读 169

leetcode 146 LRU 缓存机制

leetcode 146 LRU 缓存机制

简介

使用了C++自带的实现deque 和 unordered_map

code

class LRUCache {public:    unordered_map<int, bool> map;    unordered_map<int, int> mapV;    deque<int> q;    int capacity;
    LRUCache(int capacity) {        this->capacity = capacity;
    }    
    int get(int key) {        if(map[key]){            for(auto it=q.begin(); it != q.end(); it++){                if(*it == key){
                    q.erase(it);                    break;
                }
            }            // if(q.size() == capacity) {
            //     map[q.front()] = false;
            //     q.pop_front();
            // }
            q.push_back(key);            map[key] = true;            return mapV[key];
        }        return -1;
    }    
    void put(int key, int value) {        if(map[key]) {
            mapV[key] = value;            for(auto it=q.begin(); it != q.end(); it++){                if(*it == key){
                    q.erase(it);                    break;
                }
            }
            q.push_back(key);
        }else{            if(q.size() == capacity){                map[q.front()] = false;
                q.pop_front();
            }
            q.push_back(key);            map[key] = true;
            mapV[key] = value;
        }
    }
};/**
 * 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);
 */
class LRUCache extends LinkedHashMap<Integer, Integer>{    private int capacity;    
    public LRUCache(int capacity) {        super(capacity, 0.75F, true);        this.capacity = capacity;
    }    public int get(int key) {        return super.getOrDefault(key, -1);
    }    public void put(int key, int value) {        super.put(key, value);
    }    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {        return size() > capacity; 
    }
}

java 直接 使用了LinkedHashMap 然后 重载了removeEldestEntry函数, 对于输入的, 如果个数大于设定的容量将会删除.
java这个也太作弊了, 不过一般也很少有人会记住 LinkedHashMap这个名字.
还有removeEldestEntry这个名字.

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne

来源:https://www.cnblogs.com/eat-too-much/p/14778166.html

服务器评测 http://www.cncsto.com/ 

服务器测评 http://www.cncsto.com/ 


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐