题目

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{
private:
struct CacheNode{
int key;
int value;
CacheNode(int k, int v) : key(k), value(v) {}
};
std::list<CacheNode> cachelist;
std::map<int, std::list<CacheNode>::iterator> cacheMap;
int capacity;
public:
LRUCache(int capacity) {
this->capacity = capacity;
} int get(int key) {
if ( cacheMap.find(key) == cacheMap.end() ) return -;
cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]);
cacheMap[key] = cachelist.begin();
return cacheMap[key]->value;
} void set(int key, int value) {
if ( cacheMap.find(key)==cacheMap.end() )
{
if ( cachelist.size()==capacity )
{
cacheMap.erase(cachelist.back().key);
cachelist.pop_back();
}
cachelist.push_front(CacheNode(key,value));
cacheMap[key] = cachelist.begin();
}
else
{
cacheMap[key]->value = value;
cachelist.splice(cachelist.begin(), cachelist, cacheMap[key]);
cacheMap[key] = cachelist.begin();
}
}
};

Tips

这个题目直接参考的网上solution。

记录几个当时的疑问:

1. 为什么要结合list和hashmap两种数据结构,只用Hashmap一种数据结构不行么?

因为,如果cache满了,hashmap是无法知道哪个元素是“最不可能被访问的”,但是用双链表(std::list)这种结构却可以轻松确定这个事情。

2. 为什么CacheNode中要有key这个成员?

如果要去除“最不可能被访问的元素”,我们知道这个元素的本身value在list的最后一个位置,但是我们怎么知道这个要被删除的元素对应的hasmap中的位置呢?因此,我们需要在CacheNode这个结构体中保存key和value。这样就可以通过list最后一个元素,知道要删除的hashmap中的位置。

=================================================

第二次过这道题,比一次稍微熟练一些,但是基本还是写不出来。参照着之前的思路,又写了两边,加深印象。

class LRUCache{
private:
struct CacheNode
{
int key;
int value;
CacheNode(int k, int v): key(k), value(v){}
};
int capacity;
list<CacheNode> cacheList;
unordered_map<int, list<CacheNode>::iterator> cacheMap;
public:
LRUCache(int capacity) {
this->capacity = capacity;
} int get(int key) {
if ( cacheMap.find(key)==cacheMap.end() ) return -;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
return cacheMap[key]->value;
} void set(int key, int value) {
if ( cacheMap.find(key)==cacheMap.end() )
{
if ( cacheList.size()==capacity )
{
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front(CacheNode(key,value));
cacheMap[key] = cacheList.begin();
}
else
{
cacheMap[key]->value = value;
cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);
cacheMap[key] = cacheList.begin();
}
}
};

【LRU Cache】cpp的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 系列目录 上次的探讨没有任何结果,我浏览了大量的文章 ...

  2. ASP.NET MVC5+EF6+EasyUI 后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】

    系列目录 上次的探讨没有任何结果,我浏览了大量的文章和个别系统的参考!决定用Cache来做,这可能有点难以接受但是配合mvc过滤器来做效果非常好! 由于之前的过滤器我们用过了OnActionExecu ...

  3. hdu 4739【位运算】.cpp

    题意: 给出n个地雷所在位置,正好能够组成正方形的地雷就可以拿走..为了简化题目,只考虑平行于横轴的正方形.. 问最多可以拿走多少个正方形.. 思路: 先找出可以组成正方形的地雷组合cnt个.. 然后 ...

  4. Hdu 4734 【数位DP】.cpp

    题意: 我们定义十进制数x的权值为f(x) = a(n)*2^(n-1)+a(n-1)*2(n-2)+...a(2)*2+a(1)*1,a(i)表示十进制数x中第i位的数字. 题目给出a,b,求出0~ ...

  5. 【Unique Paths】cpp

    题目: A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). ...

  6. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  7. 【Permutations II】cpp

    题目: Given a collection of numbers that might contain duplicates, return all possible unique permutat ...

  8. 【Subsets II】cpp

    题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. ...

  9. 【Sort Colors】cpp

    题目: Given an array with n objects colored red, white or blue, sort them so that objects of the same ...

随机推荐

  1. logcat保存当前应用程序的日志并上传服务器或指定邮箱

    给大家分享一个项目中用到的日志统计并提交服务器的日志工具类.通过过得当前app的PID,采用命令行的方式实用logcat工具过滤日志.代码区: package org.and.util; import ...

  2. Linux 常用ps命令

    (1)查看系统所有进程: 标准格式:           ps -e           ps -ef           ps -eF           ps -ely   BSD格式:     ...

  3. 关于javascript 里面类型的判断

    javacript至今共有7中类型 Six data types that are primitives: Boolean Null Undefined Number String Symbol (n ...

  4. AddToDate

    AddToDate is a PeopleCode built-in function for manipulating a date in PeopleCode. You can use it to ...

  5. [leetcode]_Search Insert Position

    题目:查找元素target插入一个数组中的位置. 代码: public int searchInsert(int[] A, int target) { int len = A.length; int ...

  6. cmd中无法运行svn命令

    Svn 不是内部或外部命令,也不是可运行的程序 解决方法: 增加“svn安装目录/bin”,例如:C:\Program Files\TortoiseSVN\bin

  7. form表单无刷新提交文件(iframe)

    先看一段代码(PHP例子) 1.表单代码(form.html): <iframe name="testIframeName" style="display:none ...

  8. MapReduce作业的map task和reduce task调度参数

    MapReduce作业可以细分为map task和reduce task,而MRAppMaster又将map task和reduce task分为四种状态: 1.pending:刚启动但尚未向reso ...

  9. shopnc二次开发(一)

    ---恢复内容开始--- 以前没有怎么接触过shopnc,感觉界面挺漂亮的,不过后来自己需要开发一个电商系统,就顺便参考了下,感觉构架垃圾的一塌糊涂.不过平时做这个系统二次开发的业务比较多,所以简单的 ...

  10. Sql Server数据库之通过SqlBulkCopy快速插入大量数据

    废话不多说,直接上代码 /// <summary> /// 海量数据插入方法 /// </summary> /// <param name="connectio ...