题目

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. nodejs前端自动化构建

    http://99jty.com/?p=1257 http://www.jankerli.com/?p=1628 http://www.cnblogs.com/zhepama/archive/2013 ...

  2. POJ C++程序设计 编程题#1 大整数的加减乘除

    编程题#4:大整数的加减乘除 来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩.) 注意: 总时间限制: 1000ms 内存限制: 65536kB 描述 ...

  3. C#中的委托、事件和设计模式(转载)

    引言 委托和事件在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触C#时间不长的人来说并不容易.它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去的人 ...

  4. 大数据实践:ODI 和 Twitter (一)

    本文利用twitter做为数据源,介绍使用Oracle大数据平台及Oralce Data Integrator工具,完成从twitter抽取数据,在hadoop平台上处理数据,并最终加载到oracle ...

  5. Nginx+Tomcat+Memcached集群

    Tomcat集群session同步方案有以下几种方式: 使用tomcat自带的cluster方式,多个tomcat间自动实时复制session信息,配置起来很简单.但这个方案的效率比较低,在大并发下表 ...

  6. 【原创】解决鼠标经过子元素触发mouseout,mouseover事件的问题

    关键词:父子元素关系  mouseout  mouseover  事件  事件冒泡 初期代码: <!DOCTYPE html> <html> <head> < ...

  7. php 显示内存 释放内存

    <?php //这只是个例子,下面的数字取决于你的系统 echo memory_get_usage() . "\n"; // 36640 $a = str_repeat(&q ...

  8. ASP.NET MVC4学习笔记路由系统实现

    一.路由实现 路由系统实际是一个实现了ASP.NET IHttpModule接口的模块,通过注册HttpApplication的PostResolveRequestCache 事件对Url路由处理.总 ...

  9. 金山词霸每日一句开放平台 .NET demo

    先附上地址:http://open.iciba.com/?c=api 小金山提供了2种获取数据的方式 1. 通过填入自己的网站名称.网址.邮箱地址 来生成一段javascript脚本,直接将生成的代码 ...

  10. 自适应游标共享技术01(Adaptive Cursor Sharing)

    什么是ACS(adaptiver cursor sharing) Oracle通过绑定变量技术解决了SQL语句硬解析过多的问题,降低了资源的争用.但是绑定变量在引入cursor sharing,增加了 ...