题目:

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.

这是我的代码:

 class LRUCache{
public:
int num;
int max;
list<int> latest_key;         //用于保存使用情况,队头是最久未使用的,队尾是最近使用的
unordered_map<int, int> cache;   //用于保存key,value LRUCache(int capacity) {
num = ;
max = capacity;
} int get(int key) {
unordered_map<int, int>::iterator it = cache.find(key);
list<int>::iterator iter;
if (it == cache.end())  //如果没有找到key
return -;
else            //如果找到了key,就在对应的最近latest队列里面修改key的位置,先把key所在的位置删除,再把key放到队尾
{
iter = latest_key.begin();
while (*iter != key)
iter++;
latest_key.erase(iter);
latest_key.push_back(key);
return it->second;
}
} void set(int key, int value) {
unordered_map<int, int>::iterator it = cache.find(key);
list<int>::iterator iter;
if (it != cache.end())  //如果要插入的已经有key存在,就先在优先队列里面找到key出现的位置,删除,再把key插入队尾
{
it->second = value;
iter = latest_key.begin();
while (*iter != key)
iter++;
latest_key.erase(iter);
latest_key.push_back(key);
}
else            //如果要插入的不存在
{
if (num<max)  //如果不超过cache容量,则直接在cahe中插入,再在队尾添加该key
{
num++;
cache.insert(std::pair< int, int >(key, value));
latest_key.push_back(key);
}
else      //如果cache已经满了,则根据队头元素,在cache删除对应键值,再在队列中删除这个队头,之后,把新要插入的键值插入cache中,把新key插入队尾
{
int latest = latest_key.front();
cache.erase(latest);
latest_key.pop_front();
cache.insert(std::pair< int, int >(key, value));
latest_key.push_back(key);
}
}
}
};

  当我把代码中出现:

  iter = latest_key.begin();
while (*iter != key)
iter++;

  部分替换为:

 iter=find(latest_key.begin(),latest_key.end(),key);

  就会报错:

Time Limit Exceeded

Last executed input: 2048,[set(1178,3401),set(903,6060).....

  我大致查了一下find的实现机制,也是遍历啊,按理说这两者效率差不多,为什么替换之后就不能通过?而替换之前能通过,求大神解答!!

  万分感谢!!!

  在Leetcode上问,已经得到答案:

  之前的那个算法效率确实不高,压线过的,修改了原有代码,增加了一个unordered_map<int, list<int>iterator>用来索引list,可以使时间复杂度降到O(1):

 class LRUCache{
private:
unordered_map<int, int> cache;
unordered_map<int, list<int>::iterator> find_key;
list<int> latest_key;
int max;
public:
LRUCache(int capacity) : max(capacity){ } int get(int key) {
if (cache.find(key) == cache.end()){
return -;
}
latest_key.erase(find_key[key]);
latest_key.push_front(key);
find_key[key] = latest_key.begin();
return cache[key];
} void set(int key, int value) {
if (cache.find(key) == cache.end()) {
if (cache.size() >= max) {
cache.erase(latest_key.back());
latest_key.pop_back();
cache[key] = value;
latest_key.push_front(key);
find_key[key] = latest_key.begin();
}
else {
cache[key] = value;
latest_key.push_front(key);
find_key[key] = latest_key.begin();
}
}
else {
cache[key] = value;
latest_key.erase(find_key[key]);
latest_key.push_front(key);
find_key[key] = latest_key.begin();
}
}
};

[LeetCode]LRU Cache有个问题,求大神解答【已解决】的更多相关文章

  1. tomcat是怎么找到项目lib目录下的jar包的,求大神解答

    是通过java代码动态的修改classpath吗,和classloader有关系吗

  2. c# winfrom 页面的enter变为tab 功能使用 在特定的按钮里面如何继续当enter使用求大神帮忙解答一下 !!急

    enter 当tab  键用 已经实现  :例如按回车的时候切换一直走 ,走到一个按钮如何让回车键在这个按钮的时候还是执行enter按钮的功能而不是tab   求大神解答一下, 目前页面tab功能改为 ...

  3. 自己封装了一个EF的上下文类.,分享一下,顺便求大神指点

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  4. 刚下了VS2010不会用,求大神指点迷津

    刚下了VS2010不会用,求大神指点迷津 [菌菌][C语言MOOC]第七周计算分数精确值(10分) thinkphp3.1Calltoamemberfunctionget()onnull java提示 ...

  5. python 抓取搜狗微信出现的问题,求大神解决

    爬取到的data不是想要获取文章页面的源码,而是跳转到验证码的页面的源码.我网上查了一下是由于访问过于频繁导致的,我也加了time.sleep和改了请求头但还是显示不了,求大神支招,除了识别验证码的方 ...

  6. debug的粗略使用(求大神们补充、指教,小渣马上改)

    debug的使用 往往我们在写代码的时候会发现那种很隐秘的bug,一直找找不多,甚至开始怀疑人生.目光扫描和人脑编译又耗时又耗精力又很容易中途乱了脑子,一切得重新来,所以我写了一篇博客来模拟一下检查b ...

  7. 真想用c#开发个 wp五笔输入法。。。奈何网上资料太少,源码都是c++写的。求大神指点!!!

    真想用c#开发个 wp五笔输入法...奈何网上资料太少,源码都是c++写的.求大神指点!!!!

  8. iis频繁奔溃,求大神帮忙分析dump

    直接上图了 上图三个错误最近频繁出现,出现一次iis就奔溃一次,抓取的dump分析后如下: Couldn't resolve error at 'ls' :> !analyze -v ***** ...

  9. [转帖] select、poll、epoll之间的区别总结[整理] + 知乎大神解答 https://blog.csdn.net/qq546770908/article/details/53082870 不过图都裂了.

    select.poll.epoll之间的区别总结[整理] + 知乎大神解答 2016年11月08日 15:37:15 阅读数:2569 http://www.cnblogs.com/Anker/p/3 ...

随机推荐

  1. wordpress换域名后无法登陆的解决方案

    第一步:登录到你的数据库管理页面,找到wp_options表: 第二步:将表中的siteurl和home字段的值修改为当前的新域名,siteurl值的修改和home值的修改同理.如下图:

  2. 2326: [HNOI2011]数学作业 - BZOJ

    首先是DP,分段DP(按位数讨论) 然后每一段构造出它对应的矩阵,用矩阵快速幂加速 type matrix=..,..]of int64; var n,m:int64; a,b,c,d:matrix; ...

  3. html5 Doctor——教你规范使用html5标签

    学习地址(英文资料):http://html5doctor.com/ http://www.w3.org/html/wg/drafts/html/master/text-level-semantics ...

  4. Machine Learning for Developers

    Machine Learning for Developers Most developers these days have heard of machine learning, but when ...

  5. SOCI、LiteSQL、POCO数据库访问类库对比

    最近在做视频的开发,其中视频的设备接入管理服务器.流媒体管理服务器.中心服务器都涉及到了数据库的操作,同时需要兼容大多数版本的数据库,包括mysql.sqlite.oracle.公司原来使用的是ado ...

  6. 一分钟明白 VS manifest 原理

    什么是vs 程序的manifest文件 manifest 是VS程序用来标明所依赖的side-by-side组建,如ATL, CRT等的清单. 为什么要有manifest文件 一台pc上,用一组建往往 ...

  7. 1988-B. 有序集合

    描述 在C++里,有一个神奇的东西,叫做STL,这里提供了很多简单好用的容器,用来实现常用又很难书写的数据结构,如栈(stack)等.其中,有一个容器叫set,译作“有序集合”.首先,这是一个集合,所 ...

  8. HDU4704+费马小定理

    费马小定理题意:求s1+s2+s3+...+sn;si表示n划分i个数的n的划分的个数,如n=4,则s1=1,s2=3    利用隔板定理可知,就是求(2^n-1)%mod-----Y    现在已知 ...

  9. 【疯狂Java学习笔记】【理解面向对象】

    [学习笔记]1.Java语言是纯粹的面向对象语言,这体现在Java完全支持面向对象的三大基本特征:封装.继承.多态.抽象也是面向对象的重要组成部分,不过它不是面向对象的特征之一,因为所有的编程语言都需 ...

  10. CURL与PHP-CLI的应用【CLI篇】

    CLI的普通应用 什么是PHP-CLI php-cli是php Command Line Interface的简称,即PHP命令行接口,在windows和linux下都是支持PHP-CLI模式的; 为 ...