您的位置:首页 > 其它

146. LRU Cache

2018-03-23 15:16 225 查看
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
在面经中看过这道题,逻辑并不难,需要熟悉unordered_map、list、pair的使用方法。list用来存储缓存器队列,map用来快速查询key对应的位置,此时注意map中第二个元素类型应该是pair的iterator,这样才能指向对应的list元素。get时首先判断key是否已经在map中,若无则返回-1,若有则返回对应的list中的value。put时先判断key是否在map中,若在则把之前的list对象抹去,然后在头部插入新的list对象,同时在map中更新key值对应的对象。如果插入完成后超出容量,则pop掉list尾部元素,同时删除map中对应的元素。此题有三个关键点:1、各种容器的使用是否熟练。2、迭代器的解引用是否正确。3、list和map要同步更新和删除。容器的使用参考如下:unordered_map https://blog.csdn.net/hk2291976/article/details/51037095#334-erase pairhttps://blog.csdn.net/sinat_35121480/article/details/54728594
listhttps://www.cnblogs.com/scandy-yuan/archive/2013/01/08/2851324.html
class LRUCache {
public:
LRUCache(int capacity) {
cap=capacity;
}

int get(int key) {
auto p=m.find(key);
if(p!=m.end())
{
l.splice(l.begin(),l,p->second);
return p->second->second;
}
return -1;
}

void put(int key, int value) {
auto p=m.find(key);
if(p!=m.end())
l.erase(p->second);
l.push_front(make_pair(key,value));
m[key]=l.begin();
if(l.size()>cap)
{
m.erase(l.rbegin()->first);
l.pop_back();
}
}
private:
int cap;
list<pair<int,int>> l;
unordered_map<int,list<pair<int,int>>::iterator> m;
};

/**
* 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);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: