• 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--;
        }
        
    };
  • 相关阅读:
    BestCoder Round #65
    Codeforces Round #334 (Div. 2)
    二叉搜索树(排序二叉树)
    二叉搜索树 POJ 2418 Hardwood Species
    差分约束系统 POJ 3169 Layout
    思维题(转换) HDU 4370 0 or 1
    SPFA+Dinic HDOJ 3416 Marriage Match IV
    图论 SRM 674 Div1 VampireTree 250
    SPFA(建图) HDOJ 4725 The Shortest Path in Nya Graph
    SPFA(负环) LightOJ 1074 Extended Traffic
  • 原文地址:https://www.cnblogs.com/winscoder/p/3421876.html
Copyright © 2020-2023  润新知