题目:

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. Shiro 缓存失效以后的一个问题

    shiro 1.2.2和1.2.3 为shiro设置了缓存,但是当服务器运行几个小时后,页面判断 <shiro:hasPermission name="admin"> ...

  2. java中四种引用类型

    java中四种引用类型  今天看代码,里面有一个类java.lang.ref.SoftReference把小弟弄神了,试想一下,接触java已经有3年了哇,连lang包下面的类都不了解,怎么混.后来在 ...

  3. CQRS学习——Dpfb以及其他[引]

    [Dpfb的起名源自:Ddd Project For Beginer,这个Beginer自然就是博主我自己了.请大家在知晓这是一个入门项目的事实上,怀着对入门者表示理解的心情阅读本系列.不胜感激.] ...

  4. 团体程序设计天梯赛-练习集L1-016. 查验身份证

    L1-016. 查验身份证 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 陈越 一个合法的身份证号码由17位地区.日期编号和顺序编号 ...

  5. httpsclient 自动获取证书 无证书访问 验证过能直接用

    首先实现写一个 实现接口SecureProtocolSocketFactory的类. /** *ClassName: bcde *date: 2015年2月26日 下午4:51:01 * *@auth ...

  6. (转)eclipse快捷键

    Eclipse常用快捷键 Eclipse的编辑功能非常强大,掌握了Eclipse快捷键功能,能够大大提高开发效率.Eclipse中有如下一些和编辑相关的快捷键. 1. [ALT+/] 此快捷键为用户编 ...

  7. dtp--eclipse的安装数据源管理的一个插件的安装方法

    1.  下载eclipse dtp 插件 http://download.eclipse.org/datatools/updates/1.11 help——>install new softwa ...

  8. 64位ubuntu安装WPS

    http://jingyan.baidu.com/article/d3b74d64afd96f1f77e609a3.html http://sixipiaoyang.blog.163.com/blog ...

  9. Android开发UI之ListView中的Button点击设置

    在ListView的Item中,如果有Button控件,那么要实现Button和Item点击都有响应,可以将Item的Layout中Button的focusable属性设为false,然后设置layo ...

  10. DB2系统管理试题标准答案

    1. 如果需要创建一个表,并把表中的索引数据和其他数据分开存储,则应该 A.建立两个SMS表空间分别存储索引数据和其他数据 B.建立两个DMS表空间分别存储索引数据和其他数据 C.建立一个DMS表空间 ...