【leetcode】146. LRU Cache LRU淘汰规则的kv hash容器

1. 题目

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) – Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.

Follow up:
Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 / capacity / );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4

2. 思路

因为要求是O(1)的复杂度,因此必须要用hash来索引。要求LRU规则的淘汰,因此建立一个链表,每次对key产生访问之后,就将此kv移动到最前端。容器不够时,从末端进行淘汰。

3. 代码

class LRUCache {
private:
    typedef std::pair<int, int> Node;
    typedef std::list<Node> Cont;
    typedef Cont::iterator Iter;
    typedef std::unordered_map<int, Iter> Idx;
    
    Cont _cont;
    Idx _idx;
    int _cap;
    int _num; 
    
public:
    LRUCache(int capacity) : _cap(capacity), _num(0) {
        
    }
    
    int get(int key) {
        auto it = _idx.find(key);
        if (it == _idx.end()) {
            return -1;
        }
        Node n = *(it->second);
        _cont.erase(it->second);
        _cont.push_front(n);
        _idx[key] = _cont.begin();
        return n.second;
    }
    
    void put(int key, int value) {
        auto it = _idx.find(key);
        if (it != _idx.end()) {
            _cont.erase(it->second);
            _idx.erase(it);
            _num--;
        }
        if (_num >= _cap) {
            Node b = _cont.back();
            _cont.pop_back();
            _num -= _idx.erase(b.first);
        }
        Node n(key, value);
        _cont.push_front(n);
        _idx[key] = _cont.begin();
        _num++;
        return ; 
    }
};

/**
 * 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);
 */
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000008287914
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞