-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU_cache.java
135 lines (111 loc) · 2.73 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/**
*
* @author pulkit4tech
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.PriorityQueue;
public class LRU_cache implements Runnable {
BufferedReader c;
PrintWriter pout;
// static long mod = 1000000007;
public void run() {
try {
c = new BufferedReader(new InputStreamReader(System.in));
pout = new PrintWriter(System.out, true);
solve();
pout.close();
} catch (Exception e) {
pout.close();
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
new Thread(new LRU_cache()).start();
}
void solve() throws Exception {
lru_cache();
}
private void lru_cache(){
LRUCache cache = new LRUCache(2);
cache.set(2, 4);
cache.set(2, 5);
pout.println(cache.get(2));
cache.set(3, 1);
cache.get(2);
cache.set(5, 1);
pout.println(cache.get(2));
}
class Node{
int key;
int value;
Node pre;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
class LRUCache {
int capacity;
HashMap<Integer, Node> map = new HashMap<Integer, Node>();
Node head=null;
Node end=null;
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)){
Node n = map.get(key);
remove(n);
setHead(n);
return n.value;
}
return -1;
}
public void remove(Node n){
if(n.pre!=null){
n.pre.next = n.next;
}else{
head = n.next;
}
if(n.next!=null){
n.next.pre = n.pre;
}else{
end = n.pre;
}
}
public void setHead(Node n){
n.next = head;
n.pre = null;
if(head!=null)
head.pre = n;
head = n;
if(end ==null)
end = head;
}
public void set(int key, int value) {
if(map.containsKey(key)){
Node old = map.get(key);
old.value = value;
remove(old);
setHead(old);
}else{
Node created = new Node(key, value);
if(map.size()>=capacity){
map.remove(end.key);
remove(end);
setHead(created);
}else{
setHead(created);
}
map.put(key, created);
}
}
}
}