题目

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. 在Eclipse中查看JDK类库的源代码

    http://blog.csdn.net/a81895898/article/details/8486802 在Eclipse中查看JDK类库的源代码!!! 设置: 1.点 “window”-> ...

  2. php-resque学习笔记二(配置)

    1:前提 系统:CentOS PHP版本:PHP7     安装目录:/usr/local/php php-resque          安装目录:/home/software/php-resque ...

  3. js各种宽高(2)

    在javascript和jquery中,都有对各种高度的写法,在这里,我们就着重讲一下窗口.文档等高度的理解.(宽度和高度差不多!) jquery的各种高度 首先来说一说$(document)和$(w ...

  4. iostat命令简单说说

    tps: 每秒钟发送到的I/O请求数. Blk_read /s: 每秒读取的block数 Blk_wrtn/s: 每秒写入的block数 Blk_read: 读入的block总数 Blk_wrtn: ...

  5. mysql基本数据类型(mysql学习笔记三)

    Mysql数据类型 小数: 浮点:小数位可以变化 Float单精度默认精度6位左右 Double 双精度默认精度16位左右 支持,控制数值范围 Type(M,D) M表示所有数值位数(不包括小数点和符 ...

  6. dedecms 根据key取得联动类型(enum)值

    ---恢复内容开始--- //$key:如城市的ID,$enum_file  data/enums中的文件 function get_enum_data($key, $enum_file)    {  ...

  7. 每天进步一点--c#基础巩固,事件、委托

    要想技术有所提高,就是把有些问题真正的弄懂弄明白,我从事C#开发两年了,一直对事件委托等概念一知半解,有时候博客园上看看别的大牛的文章,看看懂了就过去了,时间长了又忘了,真正理解还是要自己动手弄些例子 ...

  8. POJ--1416

    #include <stdio.h> #include <stdlib.h> ]={};//代表有没有切割的数组 ;//输入的要被切割的数字 ]={};//切完输出的数组成的数 ...

  9. Python学习教程(learning Python)--1.2.3 Python格式化输出百分比

    在有些情况下,需要百分比输出数据,我们可以继续使用Python内建函数format来实现百分比的数据输出. >>> print(format(0.5236, '.2%')) 其结果如 ...

  10. 【原创】StickHeaderListView的简单实现,解决footerView问题

    1.前言: 前几天用了GitHub上se.emilsjolander.stickylistheaders这个组件,然后发现这个组件的listview不能添加footerView,加了footer后,滑 ...