zoukankan      html  css  js  c++  java
  • LRU Cache

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

    get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
    set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

    Code:

    class LRUCache{
    private:
        struct ListNode {
            int key;
            int val;
            ListNode *last;
            ListNode *next;
            ListNode(int x, int y) : key(x), val(y), last(NULL),next(NULL) {}
        };
        int capacity,len;
        map <int,ListNode*> cacheMap;
        ListNode *anchor;
        
    public:
        
        LRUCache(int capacity) {
            this->capacity=capacity;
            len=0;
            anchor = new ListNode(0,0);
            anchor->next=anchor;
            anchor->last=anchor;
        }
        
        int get(int key) {
            ListNode *cur=cacheMap[key];
            if(cur==NULL)
                return -1;
            moveOut(cur); // move out from list
            append(cur); // update
            return cur->val;
        }
        
        void set(int key, int value) {
            if(cacheMap[key]){ // set
                ListNode *cur=cacheMap[key];
                cur->val=value; // set a new value
                moveOut(cur); // move out from list
                append(cur); // update
                
            }else{ //insert
                if(len==capacity)
                    drop(); // if full, drop the LRU           
                ListNode *cur = new ListNode(key,value); // create a new node
                append(cur); // append the new node
                cacheMap[key]=cur; // update the map
                len++;
            }
        }
        
        void moveOut(ListNode *cur){
            cur->last->next=cur->next;
            cur->next->last=cur->last;
        }
        
        void append(ListNode *cur){
            anchor->last->next=cur;
            cur->last=anchor->last;
            anchor->last=cur;
            cur->next=anchor;
        }
        
        void drop(){
            ListNode *del = anchor->next;
            anchor->next->next->last=anchor;
            anchor->next=anchor->next->next;
            cacheMap.erase(del->key);
            delete del;
            len--;
        }
        
    };
  • 相关阅读:
    【转】使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法
    配置Linux系统ssh免密登录
    numpy的随机数组
    numpy.where和numpy.piecewise的用法
    numpy、pandas学习笔记
    数据库行存储和列存储的区别
    pandas对DataFrame对象的基本操作
    pandas中assign方法的使用
    numpy实现快速傅里叶变换
    最小二乘法在线性拟合中的使用
  • 原文地址:https://www.cnblogs.com/winscoder/p/3421876.html
Copyright © 2011-2022 走看看