【Leetcode146】LRU Cache
问题描述:
设计一个LRU Cache . LRU cache 有两个操作函数。
1.get(key)。 返回cache 中的key对应的 val 值;
2.set(key, value)。
用伪代码描述如下:
if cache中存在key then 更新value; else cache中不存在key if cache 容量超过限制 then 删除最久未访问的key else cache 容量未超过限制 then 插入新的key
问题分析:
首先了解LRU原理是:优先删除最早访问的元素。(题中说的是 invalidate the least recently used item . Least 的反义词是 most , most recently 意思是最近的, 可知 least recently 意思是距离现在最远的,也就是最早的)
在不理解错题意的情况下,我们可以知道,涉及到cache中元素访问时间更新,在get 和 set都会产生。
这道题关键是如何维护这个cache中,每个元素的访问时间。如果使用普通数组来存储每个元素的最近一次访问时间,更新操作的时间复杂度是O(1),但是查询全局最小时间的复杂度将会达到O(n))(当然这里都是指在一次set操作的情况下)。在这道题中会超时,所以这里使用了set来动态的维护每一个元素的最近一次的访问时间。因为set内部实现是一棵红黑树(也就是 平衡二叉搜索树,昨天刚刚实现了一棵二叉搜索树 好巧 今天就用到了set),所以每次更新操作(find erase insert)的时间复杂度O(log n)。最后,因为这道题的key值很小,所以可以用一个数组来哈希key值,O(1)。如果用map来哈希的话,O(log n)你会得到一个 TLE。卡常数, 我×××
ps:这道题坑爹之处 ,他把set函数定义的和STL 中set名字一模一样, 哥只能用 multiset来将就,还好这道题里有hash [key]顶着,要不就gg了。
最后代码:
class LRUCache{
public:
int cap;
LRUCache(int capacity) {
memset(isInCacheMp, , sizeof isInCacheMp);
cap = capacity;
globalTick = ;
tickSet.clear();
}
int get(int key) {
if(isInCacheMp[key] ){//在 cache中,更新tick
int oldTick = keyToTickMp[key];
tickSet.erase(oldTick);
keyToTickMp[key] = globalTick ++;
tickToKeyMp[keyToTickMp[key]] = key;
tickSet.insert(keyToTickMp[key]);
return keyToValMp[key];
}
else
return -;
}
void set(int key, int value) {
if(isInCacheMp[key]){ //key在cache中,那么更新key的value
//更新value
keyToValMp[key] = value;
//更新tick
int oldTick = keyToTickMp[key];
tickSet.erase(oldTick);//删掉原tick
keyToTickMp[key] = globalTick ++;
tickToKeyMp[keyToTickMp[key]] = key;
tickSet.insert(keyToTickMp[key]);//更新tick
}
else{//key不在cache中,加入新key
//cout<<"tick set size is "<<tickSet.size()<<endl;
//cout<<"capacity is "<<LRUCache::cap<<endl;
if(tickSet.size() >= cap){//超过容量
//删除第一个(最小的)tick 对应的key失效
int oldTick = *tickSet.find( *tickSet.begin() );
int oldKey = tickToKeyMp[oldTick];
//cout<<"old tick "<<oldTick<<" old key is "<<oldKey<<endl;
isInCacheMp[oldKey] = ;
tickSet.erase(*tickSet.begin());
}
//插入一个新的key 以及对应的 tick
isInCacheMp[key] = ;
keyToValMp[key] = value;
keyToTickMp[key] = globalTick ++;
tickToKeyMp[keyToTickMp[key]] = key;
tickSet.insert(keyToTickMp[key]);
}
}
private:
int globalTick;
/*
**每一个key拥有唯一的tick 所以size也代表当前的key个数
**tick越大代表对应的key越近被使用过
*/
multiset<int> tickSet;
map<int, int>keyToTickMp;//key对应的tick
map<int, int>tickToKeyMp;//tick对应的key
map<int, int>keyToValMp;//key对应的val
//map<int, int>isInCacheMp;//记录key是否在cache中
int isInCacheMp[];
};
good luck , 加油。
吃晚饭完,回来又看了一下,突然想到 map 不就是一颗红黑树,其实完全可以代替set,这样只开一个数据结构就可以 了。然后,重写了一下。以后使用map要用标准函数,查找时用find,不要过于迷信默认的初始化值要不会引入隐形的bug.
class LRUCache{
public:
int cap;
int usedSize;
LRUCache(int capacity) {
cap = capacity;
globalTick = ;
usedSize = ;
}
int get(int key) {
globalTick ++;
if(keyToValMp.find(key) != keyToValMp.end()){//在 cache中,更新tick
int oldTick = keyToTickMp[key];
keyToTickMp[key] = globalTick;
tickToKeyMp.erase(oldTick);
tickToKeyMp[globalTick] = key;
return keyToValMp[key];
}
else
return -;
}
void set(int key, int value) {
globalTick ++;
if(keyToValMp.find(key) != keyToValMp.end()){ //key在cache中,那么更新key的value
//更新value
keyToValMp[key] = value;
//更新tick
int oldTick = keyToTickMp.find(key) -> second;
keyToTickMp.erase(key);
keyToTickMp[key] = globalTick;
tickToKeyMp.erase(oldTick);
tickToKeyMp[globalTick] = key;
}
else{//key不在cache中,加入新key
if(usedSize >= cap){//超过容量
//删除第一个(最小的)tick 对应的key失效
int oldTick = tickToKeyMp.begin()->first;
int oldKey = tickToKeyMp.begin()->second;
tickToKeyMp.erase(oldTick);
keyToTickMp.erase(oldKey);
keyToValMp.erase(oldKey);
usedSize --;
}
//插入一个新的key 以及对应的 tick
keyToValMp[key] = value;
keyToTickMp[key] = globalTick;
tickToKeyMp[globalTick] = key;
usedSize ++;
}
}
private:
int globalTick;//全局时间滴答
map<int, int>keyToTickMp;//key对应的tick
map<int, int>tickToKeyMp;//tick对应的key
map<int, int>keyToValMp;//key对应的val
};
【Leetcode146】LRU Cache的更多相关文章
- 【LeetCode】LRU Cache 解决报告
插话:只写了几个连续的博客,博客排名不再是实际"远在千里之外"该.我们已经进入2一万内. 再接再厉.油! Design and implement a data structure ...
- 【leetcode】LRU Cache
题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...
- 【leetcode】LRU Cache(hard)★
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 【Leetcode】 LRU Cache实现
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 【LeetCode OJ】LRU Cache
Problem Link: http://oj.leetcode.com/problems/lru-cache/ Long long ago, I had a post for implementin ...
- 【leetcode刷题笔记】LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 【算法】—— LRU算法
LRU原理 LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”. 实现1 最常见的 ...
- 【Redis】LRU算法和Redis的LRU实现
LRU原理 在一般标准的操作系统教材里,会用下面的方式来演示 LRU 原理,假设内存只能容纳3个页大小,按照 7 0 1 2 0 3 0 4 的次序访问页.假设内存按照栈的方式来描述访问时间,在上面的 ...
- LeetCode146:LRU Cache
题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the ...
随机推荐
- java8的LocalDateTime真心好用(补充Period.between的大坑)
LocalDateTime.LocalDate是java8新增的时间工具类,最近使用后,真心觉得强大好用,推荐文章:https://www.liaoxuefeng.com/article/001419 ...
- Ajax_数据格式_JSON
[JSON] 1.JSON(JavaScript Object Notation)一种简单的数据格式,比xml更轻巧.JSON是JavaScript原生格式,这意味着在JavaScript中处理JSO ...
- pace.js – 网页自动加载进度条插件
网站顶部的页面加载进度条是怎么实现的,页面的加载进度百分比,有时候获取是比较麻烦的,当然也可以利用一些优秀的JavaScript插件来实现,今天就为大家介绍这样子的一款插件:pace.js. [官方网 ...
- 网上的仿QQ验证码,详细使用方法
struts2的配置 和代码 1.生成图片流 类名:VerifyCodeUtils /** * 生成图片流 * @author Administrator * */ import java.awt.C ...
- Hadoop2.0安装之非HA版
主要步骤跟Hadoop1.0(1.0安装地址)一致,主要在配置这块有更改 安装 下载地址:http://archive.apache.org/dist/hadoop/core/hadoop-2.6.5 ...
- 自己定义ViewpagerIndicator (仿猫眼,加入边缘回弹滚动效果)
一.概述 今天主要来分享个自己定义viewpagerindicator.效果主要是仿 猫眼电影 顶部的栏目切换.也就是我们常说的indicator,难度简单,为了让滑动时效果更炫酷,我在滑动到左边第一 ...
- Android天气预报+百度天气接口
首先 在准备编敲代码之前有几点准备工作 1首先须要调节Android的DNS地址. (这个我会在末尾提及) http://www.eoeandroid.com/forum.php? mod=viewt ...
- Ubuntu 13.10 安装 TeX Live 2013
注:笔者也是刚刚接触TeX系统,水平有限,若有疏漏之处还望指正. 中文解决方案 对于LaTeX中文排版,比较方便有这样的几种解决方案:LaTeX+CJK / LaTeX+XeTeX / CTeX.其中 ...
- 【OpenGL】Shader实例分析(九)- AngryBots中的主角受伤特效
转发请保持地址:http://blog.csdn.net/stalendp/article/details/40859441 AngryBots是Unity官方的一个非常棒的样例.非常有研究价值. 曾 ...
- Android开发之策略模式初探
策略模式主要定义一系列的算法,学过数据结构的朋友肯定知道,对于数组从大到小进行排序有着非常多的算法.比方冒泡.交换.高速插入等等,策略模式就是把这些算法封装成一个个独立的类.方便使用时 ...