1. 程式人生 > >[leetcode] 146. LRU Cache

[leetcode] 146. LRU Cache

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); */