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. 利用CSS实现带相同间隔地无缝滚动动画

    说明:因为在移动上主要利用CSS来做动画,所以没有考虑其他浏览器的兼容性,只有-webkit这个前缀,如果需要其他浏览器,请自行补齐. 首先解释一下什么是无缝滚动动画, 例如下面的例子 See the ...

  2. Request 传值 遇到的中文乱码问题

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="xxxx.aspx.cs&quo ...

  3. R语言练习(一)

    b = seq(from=0, to=1, by=0.001) #一次方 l1 = function(b){ b^1 } y1 = l1(b) #二次方 l2 = function(b){ b^2 } ...

  4. ubuntu安装ssh

    为了解决远程连接ubuntu服务器控制端,方便操作.ubuntu不同的版本安装方式一致!首先在ubuntu服务器下安装SSH服务linux安装命令:sudo apt-get install opens ...

  5. hdu.5212.Code(莫比乌斯反演 && 埃氏筛)

    Code Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Submi ...

  6. composer环境配置

    一 下载composer.phar http://pan.baidu.com/s/1nuDQBzz cmd命令行切换到composer.phar文件目录下 运行: echo @php "%~ ...

  7. Fedora 25 Alpha版本今天发布啦

    时隔Fedora 24发布后的3个月,Fedora项目团队非常开心的宣布任何感兴趣的用户都能下载和测试即将到来的Fedora 25操作系统的Alpha预发布版本,在Fedora 25 Alpha里程碑 ...

  8. 两款基于Jquery的图表插件

    一.EasyPieChart 页面加载时,运行initPieChart()函数,调用easyPieChart()函数,显示出图表. 代码: var initPieChart = function() ...

  9. jQuery常用操作方法及常用函数总结

    一篇 jQuery 常用方法及函数的文章留存备忘. jQuery 常见操作实现方式 $("标签名") //取html元素 document.getElementsByTagName ...

  10. (转)一个JavaWeb项目开发总结

    原文地址:http://www.cnblogs.com/lzb1096101803/p/4907775.html 一.学会如何读一个JavaWeb项目源代码 步骤:表结构->web.xml-&g ...