LRU缓存 Leetocde146. LRU Cache

class Node
{
public:

    int key_t;
    int value_t;
    Node(int key,int value):key_t(key),value_t(value)
    {
        
    }
};
class LRUCache {

public:
    list cache;//缓存 双向链表 方便插入删除
    unordered_map::iterator> m; //通过map方便查找节点位置 通过key找节点位置 前面是key 后面是双向链表当前位置的迭代器
    int capacity;
    LRUCache(int capacity) :capacity(capacity)
    {
        
    }
    void output()
    {
        cout<<"cache=====cache"<=capacity)//大于等于缓存容量 删掉尾巴
            {
                //注意顺序!!!!
                /*
                cache.pop_back();
                m.erase(cache.back().key_t);
                 */
                m.erase(cache.back().key_t);
                cache.pop_back();
            }
            //新数据直接放最前面
            cache.emplace_front(Node(key,value));
            m[key]=cache.begin();
            
        }
        else//如果存在数据已经存在
        {
            //如果链表开头 更新一下value 其他原封不动 反之 移到开头
            if(cache.front().key_t!=key)
            {
                //map更新 只动链表
                cache.erase(m[key]);
                cache.emplace_front(Node(key,value));
                m[key]=cache.begin();
            }
            else
            {
                auto cache_it=(*it).second;
                (*cache_it).value_t=value;
            }
        }
    }
};

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

解法:用一个双链表存储数据,新的元素放在最前面,访问过一次也算用过,这样排在后面的都是最少用的,容量不够,删除之,key相同的需要更新value。

146. LRU Cache

Hard

251381FavoriteShare

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

 

 

你可能感兴趣的:(算法,leetcode,链表,二叉树)