哈希结构
# 146. LRU 缓存 (opens new window)
class LRUCache {
int cap;
LinkedHashMap<Integer,Integer> cache = new LinkedHashMap<>();
public LRUCache(int capacity) {
this.cap = capacity;
}
public int get(int key) {
if(!cache.containsKey(key)){
return -1;
}
makeRecent(key);
return cache.get(key);
}
public void put(int key, int value) {
if(cache.containsKey(key)){
cache.put(key,value);
makeRecent(key);
return ;
}
if(cache.size()>=this.cap){
int oldKey = cache.keySet().iterator().next();
cache.remove(oldKey);
}
//没有该key且<size
cache.put(key,value);
}
void makeRecent(int key){
int val = cache.get(key);
cache.remove(key);
cache.put(key,val);
}
}
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
31
32
33
34
35
36
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
31
32
33
34
35
36