-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathLRU_Cache.java
67 lines (56 loc) · 1.61 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// { Driver Code Starts
import java.io.*;
import java.util.*;
import java.lang.*;
public class LRUDesign {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine());
while (t-- > 0) {
int capacity = Integer.parseInt(read.readLine());
int queries = Integer.parseInt(read.readLine());
LRUCache cache = new LRUCache(capacity);
String str[] = read.readLine().trim().split(" ");
int len = str.length;
int itr = 0;
for (int i = 0; (i < queries) && (itr < len); i++) {
String queryType = str[itr++];
if (queryType.equals("SET")) {
int key = Integer.parseInt(str[itr++]);
int value = Integer.parseInt(str[itr++]);
cache.set(key, value);
}
if (queryType.equals("GET")) {
int key = Integer.parseInt(str[itr++]);
System.out.print(cache.get(key) + " ");
}
}
System.out.println();
}
}
}
class LRUCache {
static int cap = 0;
static HashMap<Integer, Integer> map;
LRUCache(int cap) {
this.cap = cap;
map = new LinkedHashMap<>();
}
public static int get(int key) {
if (map.containsKey(key)) {
int val = map.get(key);
map.remove(key);
map.put(key, val);
return val;
}
return -1;
}
public static void set(int key, int value) {
if (map.containsKey(key)) {
map.remove(key);
} else if (map.size() == cap) {
map.remove(map.entrySet().iterator().next().getKey());
}
map.put(key, value);
}
}