[leetcode] 146. LRU Cache

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33096883/article/details/78321490
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);
 */

猜你喜欢

转载自blog.csdn.net/qq_33096883/article/details/78321490