[leetcode] 146. LRU Cache

来源:互联网 发布:自动竞价软件 编辑:程序博客网 时间:2024/06/14 03:24
  • https://leetcode.com/problems/lru-cache/description/
class LRUCache {private:    int _capacity;    list<pair<int, int> > _list;    unordered_map<int, list<pair<int, int> >::iterator> _map;public:    LRUCache(int capacity) : _capacity(capacity) {    }    int get(int key) {        auto it = _map.find(key);        if (it == _map.end()) return -1;        _list.splice(_list.begin(), _list, it->second);        return it->second->second;    }    void put(int key, int value) {        auto it = _map.find(key);        if (it != _map.end()) {            _list.splice(_list.begin(), _list, it->second);            it->second->second = value;            return ;        }        if (_map.size() == _capacity) {            int del = _list.back().first;            _list.pop_back();            _map.erase(del);        }        _list.emplace_front(key, value);        _map[key] = _list.begin();    }};/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */