-
Notifications
You must be signed in to change notification settings - Fork 0
/
lk146-LRU-LinkedHashMap.java
41 lines (38 loc) · 1.02 KB
/
lk146-LRU-LinkedHashMap.java
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
37
38
39
40
41
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;
}
makeRecently(key);
return cache.get(key);
}
public void put(int key, int value) {
if(cache.containsKey(key)){
cache.put(key,value);
makeRecently(key);
return;
}
if(cache.size()>= this.cap) {
//链表头部就是最久未使用的key
int oldestKey = cache.keySet().iterator().next();
cache.remove(oldestKey);
}
cache.put(key,value);
}
public void makeRecently(int key){
int val = cache.get(key);
cache.remove(key);
cache.put(key,val);
}
}
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache obj = new LRUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/