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 ('ll 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 is reached its capacity, it should invalidate the least recently used item before inserting a new item.
The main idea is to design an LRU-based cache, which is the last-used reservation.
There are several methods to implement LRU cache, the +HASHMAP structure implementation of the linked list, the implementation of likedhashmap (inheritance, composition), FIFO implementation.
See my blog for details:
The FIFO implementation of LIKEDHASHMAP is simple and efficient.
1 Public classLRUCache {2 3 Private intcapacity;4 5 PrivateJava.util.linkedhashmap<integer, integer> cache =NewJava.util.linkedhashmap<integer, integer> (capacity,0.75f,true) {6 @Override7 protected BooleanRemoveeldestentry (Map.entry<integer, integer>eldest) {8 returnSize () >capacity;9 }Ten }; One A PublicLRUCache (intcapacity) { - This. Capacity =capacity; - } the - Public intGetintkey) { -Integer res =Cache.get (key); - returnres==NULL? -1: res; + } - + Public voidSetintKeyintvalue) { A cache.put (key, value); at } -}
Online better answer code also has hundreds of lines, time is hundreds of milliseconds, so it seems that the JDK Linkedhashmap implementation is still very efficient.
It's best not to reinvent the wheel in unnecessary situations--the Great God
LEETCODE--LRU Cache