Skip to content

Commit 8e22824

Browse files
committed
146LRU
1 parent cad55da commit 8e22824

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

146LRU/LRUCacheSolution.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.LinkedHashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* @author jiofeng
6+
* @date 2020/3/23
7+
*/
8+
public class LRUCacheSolution {
9+
public static void main(String[] args) {
10+
LRUCache cache = new LRUCache(2);
11+
12+
cache.put(1, 1);
13+
cache.put(2, 2);
14+
System.out.println(cache.get(1));
15+
cache.put(3, 3);
16+
System.out.println(cache.get(2));
17+
cache.put(4, 4);
18+
System.out.println(cache.get(1));
19+
System.out.println(cache.get(3));
20+
System.out.println(cache.get(4));
21+
}
22+
}
23+
24+
class LRUCache extends LinkedHashMap<Integer, Integer> {
25+
26+
private int capacity;
27+
28+
public LRUCache(int capacity) {
29+
super(capacity, 0.75f, true);
30+
this.capacity = capacity;
31+
}
32+
33+
public int get(int key) {
34+
return super.getOrDefault(key, -1);
35+
}
36+
37+
public void put(int key, int value) {
38+
super.put(key, value);
39+
}
40+
41+
@Override
42+
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
43+
return super.size() > capacity;
44+
}
45+
}

0 commit comments

Comments
 (0)