• 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--;
        }
        
    };
  • 相关阅读:
    10-18 noip提高组模拟赛(codecomb)T2贪心
    vj1011:记忆化搜索
    vj1010:高精乘+细心模拟
    10-18 noip提高组模拟赛(codecomb)T1倍增[未填]
    CODEFORCES ROUND #273 DIV2
    Unkown2
    2014.first[未填]
    Unknown
    历年noip复赛试题整合
    快速幂(模板)
  • 原文地址:https://www.cnblogs.com/winscoder/p/3421876.html
Copyright © 2020-2023  润新知