[分析]
自己使用HashMap + LinkedList/ArrayList的都会超时,讨论区看到使用LinkedHashMap实现的版本[url]https://leetcode.com/discuss/42891/probably-the-best-java-solution-extend-linkedhashmap[/url],这个数据结构自己平常没用过,正好学习了~
自己使用HashMap + LinkedList/ArrayList的都会超时,讨论区看到使用LinkedHashMap实现的版本[url]https://leetcode.com/discuss/42891/probably-the-best-java-solution-extend-linkedhashmap[/url],这个数据结构自己平常没用过,正好学习了~
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);
}
}

本文介绍了一种使用Java中的LinkedHashMap实现LRU缓存的方法。通过自定义LinkedHashMap子类并重写removeEldestEntry方法,可以有效地实现LRU缓存逻辑。这种方式避免了超时问题,并提供了一个高效且易于理解的解决方案。
344

被折叠的 条评论
为什么被折叠?



