-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_146.java
86 lines (74 loc) · 2.12 KB
/
LeetCode_146.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
import java.util.*;
public class LeetCode_146 {
class LRUCache {
class Node {
int key;
int value;
Node preNode;
Node nextNode;
public Node() {
}
;
public Node(int key, int value) {
this.key = key;
this.value = value;
}
}
private HashMap<Integer, Node> cache = new HashMap<>();
private int size;
private int capacity;
private Node head, tail;
public LRUCache(int capacity) {
size = 0;
this.capacity = capacity;
head = new Node();
tail = new Node();
head.nextNode = tail;
tail.preNode = head;
}
public int get(int key) {
Node node = cache.get(key);
if (node == null)
return -1;
else {
moveToHead(node);
return node.value;
}
}
public void put(int key, int value) {
Node node = cache.get(key);
if (node == null) {
Node new_node = new Node(key, value);
cache.put(key, new_node);
addToHead(new_node);
size++;
if (size > capacity) {
cache.remove(removeTail().key);
size--;
}
} else {
node.value = value;
moveToHead(node);
}
}
public void addToHead(Node node) {
node.nextNode = head.nextNode;
node.preNode = head;
head.nextNode.preNode = node;
head.nextNode = node;
}
public void removeNode(Node node) {
node.preNode.nextNode = node.nextNode;
node.nextNode.preNode = node.preNode;
}
public void moveToHead(Node node) {
removeNode(node);
addToHead(node);
}
public Node removeTail() {
Node node = tail.preNode;
removeNode(node);
return node;
}
}
}