自己使用HashMap + LinkedList/ArrayList的都会超时,讨论区看到使用LinkedHashMap实现的版本 https://leetcode.com/discuss/42891/probably-the-best-java-solution-extend-linkedhashmap,这个数据结构自己平常没用过,正好学习了~
import java.util.LinkedHashMap; public class LRUCache { private int capacity; private Map<Integer,Integer> map; public LRUCache(int capacity) { map = new LinkedHashMap<Integer, Integer>(16, 0.75f, true) { protected boolean removeEldestEntry(Map.Entry eldest) { return size() > capacity; } }; } public int get(int key) { return map.getOrDefault(key, -1); } public void set(int key, int value) { map.put(key, value); } }