[LeetCode]LRU Cache

来源:互联网 发布:网络语音监控 编辑:程序博客网 时间:2024/06/16 19:04

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.

用unordered_map 哈希来实现O(1)的查询。

用双向队列来实现O(1)的头尾删除和指定点的删除。

写起来有些复杂,队列越前面表示最近用的多。每当set一个新节点时要放倒队列前面,同时超过容量时删除队尾的元素。所以双向队列最好。

class LRUCache{public:    struct Cache{        int key;        int value;        Cache(int a,int b):key(a),value(b){}    };        LRUCache(int capacity) {        this->capacity = capacity;    }        int get(int key) {        if(cacheMap.find(key)==cacheMap.end())            return -1; //没有找到节点        //找到节点最近使用放在最前面        else{            int ret = cacheMap[key]->value;            cacheList.erase(cacheMap[key]);            cacheList.push_front(Cache(key,ret));            cacheMap[key]= cacheList.begin();            return ret;        }    }        void set(int key, int value) { //赋值要更新,如果不是赋值是插入要插到最前面,同时注意不要超过容量        if(cacheMap.find(key)==cacheMap.end()){ //插入            if(cacheList.size()!=capacity){ //没有超过容量,记得同步更新Map                cacheList.push_front(Cache(key,value));                cacheMap[key] = cacheList.begin();            }            else{ //超出容量                cacheList.push_front(Cache(key,value));                cacheMap.erase(cacheList.back().key);                cacheList.pop_back();                cacheMap[key] = cacheList.begin();            }        }        else{ //更新值            cacheList.erase(cacheMap[key]); //删除当前节点,赋值更新要插入到最前面            cacheList.push_front(Cache(key,value));            cacheMap[key] = cacheList.begin();        }    }private:    list<Cache> cacheList; //前插,删除时间也为O(1)    unordered_map<int, list<Cache>::iterator> cacheMap; //保证查找速度为O(1),map一个int和cache迭代器    int capacity;};


0 0
原创粉丝点击