---
title: "Leetcode - LRU Cache"
author: "likesky3"
date: "2015-09-03T18:31:44Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-lru-cache"
draft: false
lastmod: "2015-09-03T18:31:44Z"
id: 2240449
url: "https://likesky3.iteye.com/blog/2240449"
---

自己使用HashMap + LinkedList/ArrayList的都会超时，讨论区看到使用LinkedHashMap实现的版本<https://leetcode.com/discuss/42891/probably-the-best-java-solution-extend-linkedhashmap>，这个数据结构自己平常没用过，正好学习了~


```java

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);
    }
}

```