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. JavaScript数组属性与方法

    Array 对象属性 属性 描述 constructor 返回对创建此对象的数组函数的引用. length 设置或返回数组中元素的数目. prototype 使您有能力向对象添加属性和方法. Arra ...

  2. Ubuntu 12 编译安装 PHP 5.4 及 问题汇总

    参考先前的文章:Ubuntu 14 编译安装 PHP 5.4.45 + Nginx 1.4.7 + MySQL 5.6.26 笔记 安装过程: ############################ ...

  3. 打开Excel的报错,提示:不能使用对象链接和嵌入

    计算机这几天在打开Excel文档的时候,提示:不能使用对象链接和嵌入, 而且出现如下的提示:Microsoft Office Excel进程已停止工作, 每次打开Excel的时候都是同样的问题,害我跟 ...

  4. jquery 表单清空

    $(':input','#myform') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .rem ...

  5. oracle 行列转换的运用

    问题: 员工表: A(E_ID,NAME,) 部门表:  B(D_ID,D_NAME) 员工与部门关系:C(ID,E_ID,D_ID) SELECT  A.E_ID,A.NAME ,B.D_NAME ...

  6. .net生成二维码

    下好QRCode.dll引用到项目中 using System; using System.Collections.Generic; using System.Linq; using System.W ...

  7. SSH-Struts第二弹:一个Form提交两个Action

    根据CSDN中的博客:http://blog.csdn.net/forwayfarer/article/details/3030259进行学习. 1.多个submit的Form表单页面 or 在jsp ...

  8. linux kernel 杂谈

    首先介绍一下背景吧,工作三个星期了.复习了一波u-boot,跟了一下事件上报,搞了下平台设备,扣了一个内存检查代码. 想想生活是不是有点无聊.对啊,真的很无聊!!!! 无聊也没有办法啊,所以找点方法去 ...

  9. centos7 关闭firewall安装iptables并配置

    一.配置防火墙,开启80端口.3306端口 CentOS 7.0默认使用的是firewall作为防火墙,这里改为iptables防火墙. 1.关闭firewall: systemctl stop fi ...

  10. 5.8---像素设定(CC150)

    注意:仔细注意位置. public static int[] renderPixel(int[] screen, int x, int y){ int[] ans = new int[screen.l ...