ITeye博客

Leetcode - LRU Cache

likesky3 · 2015-09-03 18:31 · Hash · List · 编程语言 · Markdown

自己使用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);
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。