-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathLRU.java
More file actions
57 lines (48 loc) · 1.07 KB
/
LRU.java
File metadata and controls
57 lines (48 loc) · 1.07 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
package HashMaps;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
/**
* Author - archit.s
* Date - 02/11/18
* Time - 11:26 AM
*/
public class LRU {
Map<Integer,Integer> map;
int capacity;
Deque<Integer> d;
public LRU(int capacity) {
this.capacity = capacity;
map = new HashMap<>();
d = new LinkedList<>();
}
public int get(int key) {
if(map.containsKey(key)){
d.remove(key);
d.addFirst(key);
return map.get(key);
}
else{
return -1;
}
}
public void set(int key, int value) {
if(d.size() < capacity){
if(map.containsKey(key)){
d.remove(key);
}
}
else{
if(map.containsKey(key)){
d.remove(key);
}
else{
int removedKey = d.removeLast();
map.remove(removedKey);
}
}
map.put(key,value);
d.addFirst(key);
}
}