LRU

Problem

Design and implement a LRU cache

分析

题目已经说明一切,实现一个LRU。
好,之前由于有同学上过CC这门课程,知道LinkedHashMap这种数据结构已经实现了LRU功能的,那我在这里偷了个懒,直接用了这个数据结构。
如果想更多了解LRU的情况,
请戳这里. 在这里给出了另外一种实现LRU的方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class  {

private Map<Integer, Integer> map;
public (int capacity) {
map = new LinkedHashOwnMap<>(capacity);
}

public int get(int key) {
if (map.containsKey(key)) {
return map.get(key);
} else {
return -1;
}
}

public void set(int key, int value) {
map.put(key, value);
}
static class LinkedHashOwnMap<K, V> extends LinkedHashMap<K, V> {
int capacity;

public LinkedHashOwnMap(int capacity) {
super(16, 0.75f, true);
this.capacity = capacity;
}
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}
}