-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru-cache.java
49 lines (45 loc) · 1.24 KB
/
146.lru-cache.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
42
43
44
45
46
47
48
49
class LRUCache {
LinkedHashMap<Integer, Integer> hsm;
int cap;
public LRUCache(int capacity) {
hsm = new LinkedHashMap<Integer, Integer>();
// @Override
// protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest)
// {
// return size() > capacity;
// } };
cap = capacity;
}
public int get(int key) {
if(hsm.containsKey(key)){
reorder(key,hsm.get(key));
return hsm.get(key);
}
return -1;
}
public void put(int key, int value) {
// System.out.println(hsm);
if(cap == hsm.size() && !hsm.containsKey(key)){
Map.Entry<Integer, Integer> toEvict = hsm.entrySet().iterator().next();
hsm.remove(toEvict.getKey());
}
//if(toEvict)
// hsm.removeEldestEntryM(hsm.entrySet());
reorder(key, value);
}
public void reorder(int key, int val){
if(hsm.containsKey(key)){
hsm.remove(key);
hsm.put(key, val);
}
else{
hsm.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);
*/