-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU Cache.java
92 lines (86 loc) · 2.37 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
//http://blog.csdn.net/linhuanmars/article/details/21310633
class Node
{
Node pre, next;
int key;
int val;
public Node(int key, int value)
{
this.key = key;
this.val = value;
}
}
private int capacity;
private int num;
private HashMap<Integer, Node> map;
private Node first, last;
public LRUCache(int capacity) {
this.capacity = capacity;
num = 0;
map = new HashMap<Integer, Node>();
first = null;
last = null;
}
public int get(int key) {
Node node = map.get(key);
if(node == null)
return -1;
else if(node!=last)
{
if(node == first)
first = first.next;
else
node.pre.next = node.next;
node.next.pre = node.pre;
last.next = node;
node.pre = last;
node.next = null;
last = node;
}
return node.val;
}
public void set(int key, int value) {
Node node = map.get(key);
if(node != null)
{
node.val = value;
if(node!=last)
{
if(node == first)
first = first.next;
else
node.pre.next = node.next;
node.next.pre = node.pre;
last.next = node;
node.pre = last;
node.next = null;
last = node;
}
}
else
{
Node newNode = new Node(key,value);
if(num>=capacity)
{
map.remove(first.key);
first = first.next;
if(first!=null)
first.pre = null;
else
last = null;
num--;
}
if(first == null || last == null)
{
first = newNode;
}
else
{
last.next = newNode;
}
newNode.pre = last;
last = newNode;
map.put(key,newNode);
num++;
}
}