-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
109 lines (100 loc) · 2.69 KB
/
LRUCache.java
File metadata and controls
109 lines (100 loc) · 2.69 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package Interview;
import java.util.HashMap;
class DLinkedList{
public int key;
public int value;
public int freq;
public DLinkedList pre;
public DLinkedList next;
public DLinkedList(int key,int value,int freq){
this.key = key;
this.value = value;
this.freq = freq;
}
}
public class LRUCache {
public static void main(String[] args){
LRUCache obj = new LRUCache(2);
obj.put(3,1);
obj.put(2,1);
obj.put(2,2);
obj.put(4,4);
int param_1 = obj.get(2);
}
private static HashMap<Integer,DLinkedList> map;
private static DLinkedList head;
private static DLinkedList tail;
private static int capacity;
private static int count;
private static void addNode(DLinkedList node){
node.next = head.next;
head.next.pre = node;
head.next = node;
node.pre = head;
}
private static void removeNode(DLinkedList node){
node.next.pre = node.pre;
node.pre.next = node.next;
}
private static DLinkedList selectLeastUsedNode(){
DLinkedList tmp = tail.pre;
DLinkedList result = tmp;
int min_freq = tmp.freq;
while(tmp!=head){
if(tmp.freq<min_freq){
min_freq = tmp.freq;
result = tmp;
}
tmp = tmp.pre;
}
return result;
}
public LRUCache(int capacity) {
map = new HashMap<>();
head = new DLinkedList(-1,-1,-1);
tail = new DLinkedList(-1,-1,-1);
head.pre=null;
head.next = tail;
tail.pre = head;
tail.next = null;
this.capacity = capacity;
this.count = 0;
}
public static int get(int key) {
if(map.containsKey(key)){
map.get(key).freq++;
return map.get(key).value;
}else{
return -1;
}
}
public static void put(int key, int value) {
if(capacity==0){
return;
}
if(count>=capacity){
DLinkedList tmpNode = selectLeastUsedNode();
removeNode(tmpNode);
map.remove(tmpNode.key);
count--;
}
if(map.containsKey(key)){
DLinkedList tmpNode = map.get(key);
tmpNode.value = value;
tmpNode.freq++;
removeNode(tmpNode);
addNode(tmpNode);
}else{
DLinkedList tmpNode = new DLinkedList(key,value,1);
addNode(tmpNode);
map.put(key,tmpNode);
}
count++;
}
}
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache obj = new LFUCache(capacity);
* int param_1 = obj.get(key);
* obj.put(key,value);
*/