LeetCode - LRU Cache

来源:互联网 发布:经济发展数据库 编辑:程序博客网 时间:2024/05/16 04:45

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.

class LRUCache{    list<pair<int,int> > _cache;    unordered_map<int, list<pair<int,int> > :: iterator > _map;    int _size;public:    LRUCache(int capacity) : _size(capacity) {            }        int get(int key) {        auto itor = _map.find(key); //look up bring the element to front.        if(itor == _map.end()) return -1;        movetofront(itor->second);        return _cache.front().second;    }        void set(int key, int value) {        if(_map.find(key) != _map.end()){ // key exists, update value, bring to front.            *_map[key] = make_pair(key,value);            movetofront(_map[key]);        }else{                                           //key doesn't exist,            if(_map.size() == _size){         // over-write the last node, bring to front.                _map.erase(_cache.rbegin()->first);                *_cache.rbegin() = make_pair(key,value);                movetofront(--_cache.end());            }else                _cache.emplace_front(key, value); // insert without copying to front.            _map[key] = _cache.begin(); // update key value.         }    }        void movetofront(list<pair<int,int> > :: iterator& it){        if(it != _cache.begin())            _cache.splice(_cache.begin(), _cache, it);    }};


0 0
原创粉丝点击