您的位置:首页 > 其它

LeetCode——LRU Cache

2015-10-17 23:52 429 查看
Description:

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的缓存,即最近最后用的保留。

实现LRU缓存有几种方法,链表+HashMap结构实现,LinkedHashMap的实现(继承、组合)、FIFO实现。

具体见我的博客:

这里使用LikedHashMap的组合实现,简单高效。

public class LRUCache {

private int capacity;

private java.util.LinkedHashMap<Integer, Integer> cache = new java.util.LinkedHashMap<Integer, Integer>(capacity,0.75f,true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
};

public LRUCache(int capacity) {
this.capacity = capacity;
}

public int get(int key) {
Integer res = cache.get(key);
return res==null?-1:res;
}

public void set(int key, int value) {
cache.put(key, value);
}
}




网上比较好的答案代码也有上百行,时间也是几百毫秒,这样看起来JDK中的LinkedHashMap的实现还是很高效的。

在不必要的情况下最好不要重复造轮子——大神
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: