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的组合实现,简单高效。
1 public class LRUCache { 2 3 private int capacity; 4 5 private java.util.LinkedHashMapcache = new java.util.LinkedHashMap (capacity,0.75f,true) { 6 @Override 7 protected boolean removeEldestEntry(Map.Entry eldest) { 8 return size() > capacity; 9 }10 };11 12 public LRUCache(int capacity) {13 this.capacity = capacity;14 }15 16 public int get(int key) {17 Integer res = cache.get(key);18 return res==null?-1:res;19 }20 21 public void set(int key, int value) {22 cache.put(key, value);23 }24 }
网上比较好的答案代码也有上百行,时间也是几百毫秒,这样看起来JDK中的LinkedHashMap的实现还是很高效的。
在不必要的情况下最好不要重复造轮子——大神