-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLRUCache.java
More file actions
75 lines (53 loc) · 1.52 KB
/
Copy pathLRUCache.java
File metadata and controls
75 lines (53 loc) · 1.52 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Node{
int frequency;
int value;
public Node(int value, int frequency){
this.frequency = frequency;
this.value = value;
}
public int getValue() {
return this.value;
}
public int getFrequency() {
return this.frequency;
}
}
class LRUCache {
int capacity;
Map<Integer, Node> map = new HashMap<>();
int size = 0;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.get(key) == null) {
return -1;
} else {
map.put(key, new Node(map.get(key).getValue(), this.size++));
return map.get(key).getValue();
}
}
public void put(int key, int value) {
if (map.get(key) == null) {
this.capacity--;
if (this.capacity < 0) {
int minimumLRU = Integer.MAX_VALUE;
int deleteKey = 0;
for(Map.Entry<Integer, Node> entry : map.entrySet()) {
if (entry.getValue().getFrequency() < minimumLRU) {
minimumLRU = entry.getValue().getFrequency();
deleteKey = entry.getKey();
}
}
map.remove(deleteKey);
}
}
map.put(key, new Node(value, this.size++));
}
}
/**
* 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);
*/