[LeetCode]LRU Cache有个问题,求大神解答【已解决】
题目:
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有个问题,求大神解答【已解决】的更多相关文章
- tomcat是怎么找到项目lib目录下的jar包的,求大神解答
是通过java代码动态的修改classpath吗,和classloader有关系吗
- c# winfrom 页面的enter变为tab 功能使用 在特定的按钮里面如何继续当enter使用求大神帮忙解答一下 !!急
enter 当tab 键用 已经实现 :例如按回车的时候切换一直走 ,走到一个按钮如何让回车键在这个按钮的时候还是执行enter按钮的功能而不是tab 求大神解答一下, 目前页面tab功能改为 ...
- 自己封装了一个EF的上下文类.,分享一下,顺便求大神指点
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...
- 刚下了VS2010不会用,求大神指点迷津
刚下了VS2010不会用,求大神指点迷津 [菌菌][C语言MOOC]第七周计算分数精确值(10分) thinkphp3.1Calltoamemberfunctionget()onnull java提示 ...
- python 抓取搜狗微信出现的问题,求大神解决
爬取到的data不是想要获取文章页面的源码,而是跳转到验证码的页面的源码.我网上查了一下是由于访问过于频繁导致的,我也加了time.sleep和改了请求头但还是显示不了,求大神支招,除了识别验证码的方 ...
- debug的粗略使用(求大神们补充、指教,小渣马上改)
debug的使用 往往我们在写代码的时候会发现那种很隐秘的bug,一直找找不多,甚至开始怀疑人生.目光扫描和人脑编译又耗时又耗精力又很容易中途乱了脑子,一切得重新来,所以我写了一篇博客来模拟一下检查b ...
- 真想用c#开发个 wp五笔输入法。。。奈何网上资料太少,源码都是c++写的。求大神指点!!!
真想用c#开发个 wp五笔输入法...奈何网上资料太少,源码都是c++写的.求大神指点!!!!
- iis频繁奔溃,求大神帮忙分析dump
直接上图了 上图三个错误最近频繁出现,出现一次iis就奔溃一次,抓取的dump分析后如下: Couldn't resolve error at 'ls' :> !analyze -v ***** ...
- [转帖] 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 ...
随机推荐
- Cookie Session Cache
二. 工作机制 Ø Cookie :采用的是客户端保存信息的方案. Ø Session :采用服务器端保存信息的方案. Ø Cache :利用缓存 SRAM 来"静态"的保存写入信 ...
- JavaScript里最有效率的功能特征检测方法
代码执行效率对于程序员和程序来说都是至关重要的,尤其是遇到了那些需要大量调用.反复调用的函数方法.在很多Javascript框架里你都能看到有反复调用的函数.当在使用这些框架时,我们必须小心翼翼的尽量 ...
- leetcode2 Two Sum II – Input array is sorted
Two Sum II – Input array is sorted whowhoha@outlook.com Question: Similar to Question [1. Two Sum], ...
- "Principles of Reactive Programming" 之<Actors are Distributed> (3)
Cluster 讲课的这哥们接下来讲了下Akka Cluster的使用,但是是通过把一个以前讲过的actor 系统改成使用cluster来介绍的Akka cluster. 这部分代码很多,还是直接看视 ...
- 【图说】Eclipse与Unity 3D协同工作
原地址:http://blog.csdn.net/h570768995/article/details/9355313 Eclipse开发过程中总会碰到很多的难题,如何利用好工具帮助我们更快捷的开发也 ...
- POJ 1562 && ZOJ 1709 Oil Deposits(简单DFS)
题目链接 题意 : 问一个m×n的矩形中,有多少个pocket,如果两块油田相连(上下左右或者对角连着也算),就算一个pocket . 思路 : 写好8个方向搜就可以了,每次找的时候可以先把那个点直接 ...
- CodeForce 339:A+B+C
A题:水题.. #include<stdio.h> #include<string.h> ; char s[ maxn ]; int main(){ //freopen(&qu ...
- Android 调用系统的拍相程序进行录像
xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android ...
- PowerDesigner将name自动添加到Comment注释的方法 VB代码
Option Explicit ValidationMode = True InteractiveMode = im_Batch Dim mdl ' the current model ' get t ...
- redis info命令结果释疑
redis的性能数据这块用 info 命令就可以获取的比较全面了,下面是对info信息返回值的解释: # 参考:http://redis.io/commands/info # # # Server r ...