【leetcode】LRU Cache(hard)★
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)★的更多相关文章
- 【LeetCode】LRU Cache 解决报告
插话:只写了几个连续的博客,博客排名不再是实际"远在千里之外"该.我们已经进入2一万内. 再接再厉.油! Design and implement a data structure ...
- 【leetcode】LRU Cache
题目简述: Design and implement a data structure for Least Recently Used (LRU) cache. It should support t ...
- 【Leetcode】 LRU Cache实现
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the fol ...
- 【Leetcode146】LRU Cache
问题描述: 设计一个LRU Cache . LRU cache 有两个操作函数. 1.get(key). 返回cache 中的key对应的 val 值: 2.set(key, value). 用伪代码 ...
- 【leetcode】LRU
import java.util.HashMap; import java.util.Map; public class LRUCache { private int capacity; privat ...
- 【LeetCode】设计题 design(共38题)
链接:https://leetcode.com/tag/design/ [146]LRU Cache [155]Min Stack [170]Two Sum III - Data structure ...
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...
- 【Leetcode】Pascal's Triangle II
Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...
- 53. Maximum Subarray【leetcode】
53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...
随机推荐
- 关于360的META设置,强制使用极速模式
我的网站,为了使360浏览器打开时默认为极速模式,给用户良好的体验!避免网页由于细节而导致页面布局错乱~ <!DOCTYPE HTML> <html> <head> ...
- [AngularJS] 入门
什么是AngularJS AngularJS是Google开源的一款JavaScript MVC框架,弥补了HTML在构建应用方面的不足, 其通过使用指令(directives)结构来扩展HTML词汇 ...
- PHP文件操作 读取与写入
基本知识: PHP文件系统是基于Unix系统的 文件数据基本类型:二进制数据.文本数据 文件输入流:数据从源文件到内存的流动 文件输出流:数据从内存保存到文件的流动 文件操作函数: >>& ...
- Asp.net 网站防攻击安全设置
针对已解密的_ViewStat参数漏洞整改建议:在<system.web>下添加 <machineKey validation="3DES"/> 禁用脚本调 ...
- compareTo(String str)与compareToIgnoreCase(String str)
一.compareTo(String str)方法 返回值:如果参数字符串等于此字符串,则返回值 0:如果此字符串按字典顺序小于字符串参数,则返回一个小于 0 的值:如果此字符串按字典顺序大于字符串参 ...
- 又一个绝对棒的对话框插件fancybox v1.3.4
http://www.jsfoot.com/jquery/demo/2011-07-30/fancybox/index.html jquery插件:fancybox Fancybox的特点如下: ...
- php实现图片缩放功能类
http://www.poluoluo.com/jzxy/201312/255447.html <?php /** * Images类是一个图片处理类 * @package applicatio ...
- 转载自安卓巴士 【收藏】2015必须推荐的Android框架,猿必读系列!
一.Guava Google的基于java1.6的类库集合的扩展项目,包括collections, caching, primitives support, concurrency libraries ...
- Java多线程基础知识(六)
一. Java中的线程池 线程池的作用: 1. 降低资源消耗 2. 提高响应速度 3. 提高线程的可管理性 线程池处理流程: 1. 线程池判断核心线程池线程是否都在执行任务,如果不是,则创建一个新的工 ...
- iOS 容器 addChildViewController
//在parent view controller 中添加 child view controller FirstViewController *firstViewController=[[First ...