104-LRU Cache

来源:互联网 发布:奥克洛核反应堆知乎 编辑:程序博客网 时间:2024/05/18 06:30

–146. LRU Cache My Submissions QuestionEditorial Solution
Total Accepted: 74197 Total Submissions: 469395 Difficulty: Hard
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

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

Subscribe to see which companies asked this question

设计一个key-value类型的LRU缓存:
1.首先由key-value要求可定义结构体节点
2.如何组织这些节点便于
a.快速插入或者替换
b.快速随机读取某个节点,比如从key读取value
如果cache不满:插入
如果cache满了:替换最老的
同时保持最近访问的在前面
从操作来看,要插入和随机读取并行
这个,自然想到链表,又要随机读取,那就只有靠hash了
3.如何设计数据结构
如下详解:

class LRUCache{private:    struct CacheNode{//设定key-value节点      int key;      int value;      CacheNode(int _k,int _v):key(_k),value(_v){};    };public:    LRUCache(int capacity) {//设定cache的容量        this->capacity=capacity;    }    int get(int key) {//随机访问如何做到?通过key做hash对象利用hash找到节点地址,再访问value        if(CacheMap.find(key)==CacheMap.end())//如果不在里面返回-1表示无            return -1;        else {//如果在呢,自然是重新排序缓存列表,然后重建索引            CacheList.splice(CacheList.begin(),CacheList,CacheMap[key]);            CacheMap[key]=CacheList.begin();            return CacheMap[key]->value;        }    }    void set(int key, int value) {        if(CacheMap.find(key)==CacheMap.end()){//如果不在cache里,自然是插入到cache            if(CacheList.size()==capacity){//cache满了呢?替换最老的                CacheMap.erase(CacheList.back().key);                CacheList.pop_back();            }            CacheList.push_front(CacheNode(key,value));//在头部插入新的,因为刚访问的优先级高            CacheMap[key]=CacheList.begin();        }        else{     //本来就有key-value的映射又set,所以就是更新相应的值,并加到列表首部,刚访问的嘛            CacheMap[key]->value=value;            CacheList.splice(CacheList.begin(),CacheList,CacheMap[key]);            CacheMap[key]=CacheList.begin();        }    }    list<CacheNode> CacheList;    unordered_map<int,list<CacheNode>::iterator> CacheMap;    int capacity;};
0 0