leetcode146 LRU缓存机制(Medium)

题目来源:leetcode146 LRU缓存机制

题目描述:

运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

进阶:

你是否可以在 O(1) 时间复杂度内完成这两种操作?

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4

解题思路:

class LRUCache {
public:
    LRUCache(int capacity) {
        cat=capacity;
    }
    
    int get(int key) {
        auto it=hash.find(key);
        int ans=-1;//没找到返回-1
        if(it!=hash.end()){
            ans=it->second->second;//得到key对应的value值
            data.erase(it->second);//删除原来结点
            data.push_front(make_pair(key,ans));//移动到链表的头部
            it->second=data.begin();//hash位置更新为链表的头部
        }
        return ans;
    }
    
    void put(int key, int value) {
        auto it=hash.find(key);
        if(it!=hash.end())
        {
            data.erase(it->second);//如果要找的值已经存在,删除原来位置,移动到首部
            data.push_front(make_pair(key,value));//移动到链表最前面
            hash[key]=data.begin();//更新位置为链表首部
        }
        else if(hash.size()<cat){
            data.push_front(make_pair(key,value));//在链表最前面放置结点
            hash[key]=data.begin();//更新位置为链表首部
        }
        else{
            auto it1=data.end();
            it1--;
            hash.erase(it1->first);//删掉对应的hash
            data.erase(it1);//删掉末尾最不常使用的结点
            data.push_front(make_pair(key,value));//在链表最前面放置结点
            hash[key]=data.begin();
        }

    }
private:
    int cat;
    list<pair<int,int>> data;//双向链表
    map<int,list<pair<int,int>>::iterator> hash;//key值和在双向链表中的位置
};

/**
 * 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);
 */
原文地址:https://www.cnblogs.com/yjcoding/p/13432093.html