运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得关键字 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得关键字 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lru-cache
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
实现思路:查找和插入的时间复杂度都需要是O(1),那么只能通过hash表+双向链表的方式实现(LinkedHashMap就是这种方式),所以这里直接通过继承LinkedHashMap的方式进行实现。
通过LinkedHashMap的源码可以知道,在LinkedHashMap构造方法中,多了一个AccessOrder字段,这是一个Boolean类型字段,标识插入数据的排序类型(false 为插入顺序,true为访问顺序),所以这里我们需要设置为true。
/**
* Returns <tt>true</tt> if this map should remove its eldest entry.
* This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
* inserting a new entry into the map. It provides the implementor
* with the opportunity to remove the eldest entry each time a new one
* is added. This is useful if the map represents a cache: it allows
* the map to reduce memory consumption by deleting stale entries.
*
* <p>Sample use: this override will allow the map to grow up to 100
* entries and then delete the eldest entry each time a new entry is
* added, maintaining a steady state of 100 entries.
* <pre>
* private static final int MAX_ENTRIES = 100;
*
* protected boolean removeEldestEntry(Map.Entry eldest) {
* return size() > MAX_ENTRIES;
* }
* </pre>
*
* <p>This method typically does not modify the map in any way,
* instead allowing the map to modify itself as directed by its
* return value. It <i>is</i> permitted for this method to modify
* the map directly, but if it does so, it <i>must</i> return
* <tt>false</tt> (indicating that the map should not attempt any
* further modification). The effects of returning <tt>true</tt>
* after modifying the map from within this method are unspecified.
*
* <p>This implementation merely returns <tt>false</tt> (so that this
* map acts like a normal map - the eldest element is never removed).
*
* @param eldest The least recently inserted entry in the map, or if
* this is an access-ordered map, the least recently accessed
* entry. This is the entry that will be removed it this
* method returns <tt>true</tt>. If the map was empty prior
* to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
* in this invocation, this will be the entry that was just
* inserted; in other words, if the map contains a single
* entry, the eldest entry is also the newest.
* @return <tt>true</tt> if the eldest entry should be removed
* from the map; <tt>false</tt> if it should be retained.
*/
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
通过以上注释,可以知道,如果我们想出发LRU,只需要重写removeEldestEntry控制什么时候返回true就可以实现了。
具体代码如下:
class LRUCache {
private SelfMap map;
public LRUCache(int capacity) {
map = new SelfMap(capacity,0.75f,true);
}
public int get(int key) {
return Integer.valueOf(map.get(key).toString());
}
public void put(int key, int value) {
map.put(key, value);
}
class SelfMap extends LinkedHashMap{
private int cap;
public SelfMap(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
this.cap = initialCapacity;
}
public SelfMap(int initialCapacity) {
super(initialCapacity);
this.cap = initialCapacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return this.size() > this.cap;
}
public Object get(int key) {
return super.getOrDefault(key, -1);
}
public Object put(int key, int value) {
return super.put(key, value);
}
}
}
力扣执行结果:
LRU缓存机制(基于LinkedHashMap)
原文:https://www.cnblogs.com/ymqj520/p/13634002.html