leetcode——LRU Cache
来源:互联网 发布:编程字体推荐 编辑:程序博客网 时间:2024/06/05 08:15
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.
题目分析:
LRU 是将最不常用的换出。因此,对于每一片cache都需要有更新迭代的记录。
首先我想到了如下结构:
class Node { int key; int val; private Node(int key, int val){ this.key = key; this.val = val; } }但是随后一想,这不就是hashmap么。而选用什么样的hashmap能够自动记录最不常用的key-value对呢?
经过调研,LinkedHashMap最能胜任。其构造函数:
map = new LinkedHashMap<Integer, Integer>(capacity,(float)0.5,true);参数1:容量
参数2:负载因子(值越大,查找越慢,默认0.75)
参数3:排序是否保持跟插入顺序(更新顺序)一致
这样,记录最不常用的一个cache,就一定是该map的第一个键值对。
在set方法中,判断一下是否size达到了capacity即可。
public void set(int key, int value) { if(map.size()<capacity || map.containsKey(key)) map.put(key,value); else{ Iterator<Integer> it = map.keySet().iterator(); int itt = it.next(); map.remove(itt); map.put(key,value); } }AC代码:
import java.util.Iterator;import java.util.LinkedHashMap;/** * Created by Ghost on 2014/10/8 0008. */public class LRUCache { public int capacity; public LinkedHashMap<Integer,Integer> map; public LRUCache(int capacity) { this.capacity = capacity; this.map = new LinkedHashMap<Integer, Integer>(capacity,(float)0.5,true); } public int get(int key) { if(map.containsKey(key)) return map.get(key); return -1; } public void set(int key, int value) { if(map.size()<capacity || map.containsKey(key)) map.put(key,value); else{ Iterator<Integer> it = map.keySet().iterator(); int itt = it.next(); map.remove(itt); map.put(key,value); } }}
0 0
- LeetCode——LRU Cache
- leetcode——LRU Cache
- leetcode 146 —— LRU Cache
- LeetCode—LRU Cache解题报告
- LeetCode146—LRU Cache
- LeetCode LRU 缓存 LRU Cache
- Leetcode——146. LRU Cache 一个优雅的LRU的C++实现
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- [LeetCode]LRU Cache
- [LeetCode] LRU Cache
- leetcode LRU Cache
- LeetCode题解:LRU Cache
- LeetCode | LRU Cache
- hdu 5090(贪心)
- ubuntu 14.04 LTS下Hadoop源代码环境搭建
- 机器学习之逻辑回归(Logistic Regression)
- 某游戏开发整理(1)
- Json简介
- leetcode——LRU Cache
- java基础知识篇(1)
- Android中屏幕密度和图片大小的关系分析
- 在DDMS中访问/data目录的方法
- tinyxml使用
- csdn首页高校编程挑战金色十月线上编程比赛第二题:解密
- ora-01033:oracle initialization or shutdown in progress 解决方法
- java内存管理的小技巧
- 机器学习之逻辑回归(Logistic Regression)