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.this

思路:get函數在Cache查找key的值,若是存在於Cache中,則將該鍵值移到Cache首位置,並返回值value反之,則返回-1;set(key,value)函數,若是key存在,則更新相應的value把該元素放到最前面。若是不存在,則建立,並放到最前面,若是容器滿了,就把最後那個元素去除。從這能夠看出,元素訪問的前後是有必定的順序的,咱們能夠採用map來對元素進行快速查找,而後定位到查找的結點,使用雙向鏈表來進行移動或刪除都很方便。這裏使用STL中list容器對於移動或刪除都比較容易,代碼也比較簡潔。spa

struct CacheNode
{
    int key;
    int value;
    CacheNode(int k,int v):key(k),value(v){}
};
class LRUCache{
private:
    int size;
    list<CacheNode> cacheList;
    unordered_map<int,list<CacheNode>::iterator > cacheMap;
public:
    LRUCache(int capacity) {
        this->size=capacity;
    }
    
    int get(int key) {
        if(cacheMap.find(key)!=cacheMap.end())
        {
            list<CacheNode>::iterator iter=cacheMap[key];
            cacheList.splice(cacheList.begin(),cacheList,iter);
            cacheMap[key]=cacheList.begin();
            return cacheList.begin()->value;
        }
        else
            return -1;
    }
    
    void set(int key, int value) {
        if(cacheMap.find(key)==cacheMap.end())
        {
            if(cacheList.size()==size)
            {
                cacheMap.erase(cacheList.back().key);
                cacheList.pop_back();
            }
            cacheList.push_front(CacheNode(key,value));
            cacheMap[key]=cacheList.begin();
        }
        else
        {
            list<CacheNode>::iterator iter=cacheMap[key];
            cacheList.splice(cacheList.begin(),cacheList,iter);
            cacheMap[key]=cacheList.begin();
            cacheList.begin()->value=value;
        }
    }
};
相關文章
相關標籤/搜索