-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlruCache.java
76 lines (72 loc) · 1.66 KB
/
lruCache.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
public class Solution {
class node {
int key;
int data;
node next;
node prev;
public node(int key,int val) {
data = val;
this.key=key;
}
}
int capacity;
node head=null;
node end=null;
Map<Integer,node> map=new HashMap<>();
public Solution(int capacity) {
this.capacity=capacity;
}
public int get(int key) {
if(map.containsKey(key))
{
remove(map.get(key));
SetHead(map.get(key));
return map.get(key).data;
}
return -1;
}
public void set(int key, int value) {
if(map.containsKey(key))
{
node n=map.get(key);
n.data=value;
remove(n);
SetHead(n);
}
else {
node n=new node(key,value);
if(map.size()>=capacity)
{
map.remove(end.key);
remove(end);
SetHead(n);
}
else
{
SetHead(n);
}
map.put(key,n);
}
}
public void SetHead(node temp) {
temp.next = head;
temp.prev = null;
if (head != null)
head.prev = temp;
head = temp;
if (end == null)
end = head;
}
public void remove(node temp) {
if (temp.prev != null) {
temp.prev.next = temp.next;
} else {
head = temp.next;
}
if (temp.next != null) {
temp.next.prev = temp.prev;
} else {
end = temp.prev;
}
}
}