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.

思路:

这题吧,思路挺清楚的,就是每次get, set时都把对应的数据设为时间最近的数据,如果满了,就在set时把最老的数据扔掉,把新的插入到最近的位置。

关键是,如何在O(1)的时间内get到所需的数据,如何在O(1)的时间内,找到最老的数据。

第一个问题可以用unordered_map轻松解决,但是,第二个问题我就不会了。我很low的用了遍历,果断超时了。看答案后发现,要用list的splice函数解决。

把所有的数据按照访问时间由近到远存放在一个list中,当再次访问里面的数据时,就把该数据移动到list的开始位置,满了后就移除list的最后一个元素。

上大神的答案:

class LRUCache {
private:
// A list of (key, value) pairs
list<pair<int, int>> items;
// Map items to iterators (pointers) to list nodes
unordered_map<int, list<pair<int, int>>::iterator> cache;
// The capacity of the list
int capacity; public:
LRUCache(int capacity) : capacity(capacity) {} int get(int key) {
// If key is not found in hash map, return -1
if (cache.find(key) == cache.end())
return -;
// Move the (key, value) pair to the beginning of the list
items.splice(items.begin(), items, cache[key]);
return cache[key]->second;
} void set(int key, int value) {
// The key is not in the hash table
if (cache.find(key) == cache.end()) {
// If the cache is full then delete the least recently
// used item, which is at the end of the list
if (items.size() == capacity) {
cache.erase(items.back().first);
items.pop_back();
}
items.push_front(make_pair(key, value));
cache[key] = items.begin();
} else {
// Update the value associated with the key
cache[key]->second = value;
// Move the (key, value) pair to the beginning of the list
items.splice(items.begin(), items, cache[key]);
}
}
}

我的代码,时间是用自己设的time来记录的,超时了。

typedef struct Data
{
int value;
int time;
Data(){}
Data(int v, int t) : value(v), time(t){}
}Data; class LRUCache{
public:
LRUCache(int capacity) {
t = ; //初始化时间
c = capacity; //初始化容量
} int get(int key) {
unordered_map<int, Data>::iterator it = record.find(key);
if(it == record.end())
{
return -;
}
else
{
it->second.time = t++;
return it->second.value;
} } void set(int key, int value) {
if(record.find(key) != record.end())
{
record[key].value = value;
record[key].time = t++;
return;
}
if(record.size() == c) //容量已经达到
{
unordered_map<int, Data>::iterator replace = record.begin();
for(unordered_map<int, Data>::iterator it = record.begin(); it != record.end(); it++)
{
replace = (it->second.time < replace->second.time) ? it : replace;
}
record.erase(replace); //删掉时间最早的
} Data newData(value, t);
record[key] = newData;
t++;
}
private:
unordered_map<int, Data> record;
int c;
int t;
};

【leetcode】LRU Cache(hard)★的更多相关文章

  1. 【LeetCode】LRU Cache 解决报告

    插话:只写了几个连续的博客,博客排名不再是实际"远在千里之外"该.我们已经进入2一万内. 再接再厉.油! Design and implement a data structure ...

  2. 【leetcode】LRU Cache

    题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...

  3. 【Leetcode】 LRU Cache实现

    Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...

  4. 【Leetcode146】LRU Cache

    问题描述: 设计一个LRU Cache . LRU cache 有两个操作函数. 1.get(key). 返回cache 中的key对应的 val 值: 2.set(key, value). 用伪代码 ...

  5. 【leetcode】LRU

    import java.util.HashMap; import java.util.Map; public class LRUCache { private int capacity; privat ...

  6. 【LeetCode】设计题 design(共38题)

    链接:https://leetcode.com/tag/design/ [146]LRU Cache [155]Min Stack [170]Two Sum III - Data structure ...

  7. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  8. 【Leetcode】Pascal&#39;s Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  9. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

随机推荐

  1. 开始使用 Markdown

    (Xee:我最近感觉nyfedit打开有点慢,数据库有点大,试想着用一些其他的方式记录一下学习的过程,才想起了遗忘了很长时间的Markdown,将其分类在HTML下,也是我原本意愿的...) 本文面向 ...

  2. 使用Minify来优化网站性能

    Minify 是用PHP5开发的应用,通过遵循一些Yahoo的优化规则来提高网站的性能.它会合并多个CSS或者JavaScript文件,移除一些不必要的空格和注释,进行gzip压缩,并且会设置浏览器的 ...

  3. 如何自定义wordpress登录界面的Logo

    每次登录wp后台都会看到wordpress的logo,会不会有点烦呢?想不想换个新的.自己设定一个呢?那么如何自定义wordpress登录界面的Logo呢? 把代码复制到当前主题的 functions ...

  4. 【C语言入门教程】3.1 程序的 3 种基本结构

    程序设计是一个问题求解的过程,解决问题的步骤可看作是程序的控制结构.简单地说,程序的运行过程就是数据输入.数据处理.数据输出 3 个步骤.其中,数据处理过程是否快捷和准确,主要依赖于程序控制结构的设计 ...

  5. mysql基础面试

    php面试题之五--MySQL数据库(基础部分) 五.MySQL数据库 mysql_num_rows() mysql_affected_rows() 这两个函数都作用于 mysql_query($qu ...

  6. fontconfig编译出错

    编译fontconfig编译时出错: 出错configure: error: You must have freetype installed; see http://www.freetype.org ...

  7. CSS3-transform,2D动画实例

    对元素进行移动.缩放.转动.拉长 或 拉伸 全部都需要加前缀. Transform-2D转换方法:rotate()旋转.scale()缩放.skew()扭曲/倾斜.translate()位移.matr ...

  8. 跟着百度学PHP[4]OOP面对对象编程-5-内部引用$this

    $this就是对象内部代表这个对象的引用 可以调用被封装的方法或者属性! <?php class Person{ private $name; "; var $sex; functio ...

  9. 把ZenCart在线商店搭建到本地

    前些日子,要给在线的zencart商店做一些小改动,需要安装一个插件.大家都知道,zencart有很多插件选用,兼容性也好坏不一,直接在正在运营的网站程序上修改,难免会影响到客户体验,出什么差错了代价 ...

  10. phpcms模块开发简易教程

    简介: 在phpcms中,各个功能是以模块为单位定义的(对应modules目录),如果需要新增功能最好的办法就是开发一个模块,然后复制到phpcms目录下,然后进入后台安装即可. 官方说明: phpc ...