题目:

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. WDS无线桥接

    因为放假回家,长时间不在家,家里也没什么人,所以也就没有网可以用.为了两个月办宽带又不值得,太过浪费了.于是就只能蹭网用了.当然,要和邻居打个招呼或者你能搞定密码的情况下不打招呼(嘿嘿...).但是有 ...

  2. textarea中限制输入字符长度(实用版)

    textarea称文本域,又称文本区,即有滚动条的多行文本输入控件,在网页的提交表单中经常用到.与单行文本框text控件不同,它不能通过maxlength属性来限制字数,为此必须寻求其他方法来加以限制 ...

  3. uva 10940

    数学 打了个表 找一下规律.... #include <cstdio> int a[30]; void init() { a[1]=2;a[2]=4;a[3]=8;a[4]=16;a[5] ...

  4. robots.txt协议-互联网robots搜索规范

    最近在看搜索爬虫相关的,挺有趣的,记录一些信息备用. robots.txt官方说明网站 http://www.robotstxt.org/ robots.txt原则 Robots协议是国际互联网界通行 ...

  5. PJSIP在windows(xp或者win7)下的编译,编译工具是vs2008,PJSIP版本2.3

    PJSIP是一个开源的SIP协议库,它实现了SIP.SDP.RTP.STUN.TURN和ICE.PJSIP作为基于SIP的一个多媒体通信框架提供了非常清晰的API,以及NAT穿越的功能.PJSIP具有 ...

  6. 217. Contains Duplicate

    题目: Given an array of integers, find if the array contains any duplicates. Your function should retu ...

  7. R语言笔记:快速入门

    1.简单会话 > x<-c(1,2,4) > x [1] 1 2 4 R语言的标准赋值运算符是<-.也可以用=,不过不建议用它,有些情况会失灵.其中c表示连接(concaten ...

  8. python学习笔记二--列表

    一.列表: 1. 任意类型对象的位置相关的有序集合. 2. 没有固定大小. 3. 对偏移量进行赋值及各种方法的调用,修改列表. 4. 列表是序列的一种. 5. 所有对字符串的序列操作对列表均适用. 二 ...

  9. 高难度(1)什么是AR

    在介绍增强现实(AR)之前,需要先说说虚拟现实(VR) 虚拟现实是从英文Virtual Reality 一词翻译过来的,简称VR.VR 技术是采用以计算机技术为核心的技术,生成逼真的视.听.触觉等一体 ...

  10. eclipse不自动弹出提示(Alt+/ 快捷键失效)

    转自:http://www.cnblogs.com/shaweng/archive/2013/09/26/3340016.html 主要有一下几种方法:    1.次方法用于没有一点提示的情况:依次打 ...