Q:设计和实现最近最少使用(LRU)缓存的数据结构。它应该支持以下操作:get和set。
get(key)—如果键存在于缓存中,则获取键的值(总是正的),否则返回-1。
put(key, value)——如果键不存在,则设置或插入该值。当缓存达到其容量时,它应该在插入新项之前使最近最少使用的项无效。
你能在O(1)时间复杂度下做这两个操作吗?
举例:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
A:
LRU算法:最近最少使用,简单来说就是将数据块中,每次使用过的数据放在数据块的最前端,然后将存在的时间最长的,也就是数据块的末端的数据剔除掉这就是LRU算法。
1.使用LinkedHashMap。LinkedHashMap是有序的,且默认为插入顺序。
public class LRUCache extends LinkedHashMap<Integer, Integer> {
private int capacity;
public LRUCache(int capacity) {
super(capacity, 0.1f, true);//参数accessOrder就是用来指定是否按访问顺序,如果为true,就是访问顺序
this.capacity = capacity;
}
public int get(int key) {
return super.getOrDefault(key, -1);
}
public void put(int key, int value) {
super.put(key, value);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > capacity;
}
}
2.哈希表+双向链表(这个之后有时间做)